Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert csv file to json object datatable

Does anyone know how to get a csv url file and convert it to a json object so that I can use google charting tools in js?

like image 920
locoboy Avatar asked Aug 30 '10 18:08

locoboy


People also ask

Which method is used to convert JSON data to object?

JSON.parse() The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.


2 Answers

I realise this is an old question, but I came across it today needing to do the same thing and wrote a script to do it. You can check it out at my github repo.

The following code would accomplish what you're after (using jQuery):

$.ajax("http://my.domain.com/mycsvfile.csv", {
    success: function(data) {
        var jsonobject = csvjson.csv2json(data);
        // Now use jsonobject to do some charting...
    },
    error: function() {
        // Show some error message, couldn't get the CSV file
    }
});

Happy coding :)

like image 59
aaronsnoswell Avatar answered Oct 01 '22 13:10

aaronsnoswell


use this code for guide to parse csv file to json ...

function processFiles(files) {
    var file = files[0];
    var reader = new FileReader();
    reader.onload = function (e) {
        var output = document.getElementById("fileOutput");
        var texto = e.target.result;
        csvJSON(texto);
    };
    reader.readAsText(file);
}
function csvJSON(csv) {
    var lines = csv.split("\n");
    var result = [];
    var headers;
    for (var i = 0; i < lines.length; i++) {
        headers = lines[i].split("\n");
    }
    var cont = 0;
    for (var i = 0; i < lines.length; i++) {

        var obj = {};
        var currentline = lines[i].split("\n");
        for (var j = 0; j < headers.length; j++) {
            obj[cont] = currentline[j];
        }
        cont++;
        result.push(obj);
    }

    return JSON.stringify(result); //JSON
}
like image 20
Enrikisimo Lopez Ramos Avatar answered Oct 01 '22 15:10

Enrikisimo Lopez Ramos