6

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>
3
  • Why not just turn the CSV into an array and loop through each row? This sounds like an odd problem. Commented Aug 21, 2013 at 10:47
  • 1
    What have you already tried? Also: you shouldn't need jQuery for this -- vanilla JavaScript would suffice. Commented Aug 21, 2013 at 10:49
  • 2
    Your description suggests that you've written no code so far. Do you really need help with every single step involved? Just the term "load a file" can have a whole universe of meanings. Commented Aug 21, 2013 at 10:50

4 Answers 4

7

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

Sign up to request clarification or add additional context in comments.

Comments

4

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>

1 Comment

This skips empty cells
1

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);
});

Comments

0

I think jquery csv plugin will be helpful to convert your CSV to an array, then you can use jquery json. BTW, you can use $.get() to read your CSV file from server.

1 Comment

can u provide snippet for the same for refrence?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.