Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV to JSON using jquery

I have file in csv format:

info,value
"off to home","now"
"off to office","tomorrow"

I want json out of this using jquery but couldnt find any help.Isnt it possible to use jquery for this?

My intended output is :

 {
        "items": [
            {
                "info": "off to home",
                "value": "now"
            },
            {
                "info": "off to office",
                "value": "tomorrow"
            },

        ]
    }

PFB the code which i implemented. but it is not working

<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script src="csvjson.js"></script>
        <script>
$.ajax("data.csv", {
    success: function(data) {
        var jsonobject = csvjson.csv2json(data);
       alert(jsonobject);
    },
    error: function() {
        alert("error")
    }
});
</script>
</head>
<body>

</body>
</html>
like image 401
Aquarius24 Avatar asked Aug 21 '13 10:08

Aquarius24


3 Answers

Using jquery-csv, specifically the toObjects() method

$.ajax({
    url: "data.csv",
    async: false,
    success: function (csvd) {
        var items = $.csv.toObjects(csvd);
        var jsonobject = JSON.stringify(items);
        alert(jsonobject);
    },
    dataType: "text",
    complete: function () {
        // call a function on complete 
    }
});

Note: You'll need to import the jquery-csv library for this to work.

What this does is transform the CSV data into an array of objects.

Since the first line contains headers, jquery-csv knows to use those as the keys.

From there the data is transformed to JSON using stringify().

If you need a wrapper object, just create one and attach the data to it.

var wrapper = {};
wrapper.items = items;
alert(wrapper);

Disclaimer: I'm the author of jquery-csv

like image 131
Evan Plaice Avatar answered Nov 09 '22 21:11

Evan Plaice


Useful link, I have found. Maybe help someone.

http://jsfiddle.net/sturtevant/AZFvQ/

function CSVToArray(strData, strDelimiter) {
    // Check to see if the delimiter is defined. If not,
    // then default to comma.
    strDelimiter = (strDelimiter || ",");
    // Create a regular expression to parse the CSV values.
    var objPattern = new RegExp((
    // Delimiters.
    "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
    // Quoted fields.
    "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
    // Standard fields.
    "([^\"\\" + strDelimiter + "\\r\\n]*))"), "gi");
    // Create an array to hold our data. Give the array
    // a default empty first row.
    var arrData = [[]];
    // Create an array to hold our individual pattern
    // matching groups.
    var arrMatches = null;
    // Keep looping over the regular expression matches
    // until we can no longer find a match.
    while (arrMatches = objPattern.exec(strData)) {
        // Get the delimiter that was found.
        var strMatchedDelimiter = arrMatches[1];
        // Check to see if the given delimiter has a length
        // (is not the start of string) and if it matches
        // field delimiter. If id does not, then we know
        // that this delimiter is a row delimiter.
        if (strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter)) {
            // Since we have reached a new row of data,
            // add an empty row to our data array.
            arrData.push([]);
        }
        // Now that we have our delimiter out of the way,
        // let's check to see which kind of value we
        // captured (quoted or unquoted).
        if (arrMatches[2]) {
            // We found a quoted value. When we capture
            // this value, unescape any double quotes.
            var strMatchedValue = arrMatches[2].replace(
            new RegExp("\"\"", "g"), "\"");
        } else {
            // We found a non-quoted value.
            var strMatchedValue = arrMatches[3];
        }
        // Now that we have our value string, let's add
        // it to the data array.
        arrData[arrData.length - 1].push(strMatchedValue);
    }
    // Return the parsed data.
    return (arrData);
}

function CSV2JSON(csv) {
    var array = CSVToArray(csv);
    var objArray = [];
    for (var i = 1; i < array.length; i++) {
        objArray[i - 1] = {};
        for (var k = 0; k < array[0].length && k < array[i].length; k++) {
            var key = array[0][k];
            objArray[i - 1][key] = array[i][k]
        }
    }

    var json = JSON.stringify(objArray);
    var str = json.replace(/},/g, "},\r\n");

    return str;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
like image 43
Shoaib Ijaz Avatar answered Nov 09 '22 20:11

Shoaib Ijaz


You can use Alasql library. Alasql can load the data file from server, parse it and put the result to array of JSON objects.

This is the code:

<script src="alasql.min.js"></script>
<script>
    alasql('SELECT * FROM CSV("items.csv",{headers:true})',[],function(res){
        var data = {items:res};
    });
</script>

If you want to modify data (for example, use only one column or filter), you can do it "on the fly". Alasql understands the headers and use them for SELECT statement:

alasql('SELECT info FROM CSV("items.csv") WHERE value = "now"',[],function(res){
     console.log(res);
});
like image 1
agershun Avatar answered Nov 09 '22 21:11

agershun