3

How to convert an array of json object to csv ?

ex

[{ name: "Item 1", color: "Green", size: "X-Large" },
 { name: "Item 2", color: "Green", size: "X-Large" },
 { name: "Item 3", color: "Green", size: "X-Large" }];

give

name;color;size
Item 1;Green;X-Large
Item 2;Green;X-Large
Item 3;Green;X-Large
2

3 Answers 3

5

Example in JSFiddle : http://jsfiddle.net/FLR4v/

Dependencies :

The function

 /**
 * Return a CSV string from an array of json object
 *
 * @method JSONtoCSV
 * @param {Object} jsonArray an array of json object
 * @param {String} [delimiter=;] delimiter
 * @param {String} [dateFormat=ISO] dateFormat if a date is detected
 * @return {String} Returns the CSV string
**/
function JSONtoCSV(jsonArray, delimiter, dateFormat){
    dateFormat = dateFormat || 'YYYY-MM-DDTHH:mm:ss Z'; // ISO
    delimiter = delimiter || ';' ;

    var body = '';
    // En tete
    var keys = _.map(jsonArray[0], function(num, key){ return key; });
    body += keys.join(delimiter) + '\r\n';
    // Data
    for(var i=0; i<jsonArray.length; i++){
        var item = jsonArray[i];
        for(var j=0; j<keys.length; j++){
            var obj = item[keys[j]] ;
            if (_.isDate(obj)) {                
                body += moment(obj).format(dateFormat) ;
            } else {
                body += obj ;
            }

            if (j < keys.length-1) { 
                body += delimiter; 
            }
        }
        body += '\r\n';
    }

    return body;
}
Sign up to request clarification or add additional context in comments.

1 Comment

This does not handle strings containing the separator or escape values (if enclosed in quotes). If you know that your data will not contain it, it's fine enough.
1

Even though this is pretty old question, saving my findings here for future researchers.

Javascript now provides the feature of Object.values which can pull all values of a json to an array, which can then be converted to csv using join.

var csvrecord = Object.keys(jsonarray[0]).join(',') + '\n'; 
jsonarray.forEach(function(jsonrecord) {
   csvrecord += Object.values(jsonrecord).join(',') + '\n';
});

Only limitation is that it is still not supported by a few browsers.

1 Comment

This works only if your objects are "simple". If your jsonrecord contains a datetime object or a bizarre object, what object.values will write.
-2
function getCSVFromJson(k)
{
var retVal=[];
k.forEach(function(a){
var s=''; 
for(k in a){
    s+=a[k]+';';
}   

retVal.push(s.substring(0,s.length-1));
});
return retVal;
}

1 Comment

It's better if you explain why your code solves the problem. Please, see How to Answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.