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
Farandole
  • 539
  • 2
  • 8
  • 23
  • possible duplicate of [How to convert JSON to CSV format and store in a variable](http://stackoverflow.com/questions/8847766/how-to-convert-json-to-csv-format-and-store-in-a-variable) – jcubic Mar 13 '13 at 09:39
  • 1
    In my function, I have added header and dateformat are supported – Farandole Mar 13 '13 at 09:45

3 Answers3

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;
}
Farandole
  • 539
  • 2
  • 8
  • 23
  • 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. – Risadinha Aug 19 '22 at 14:56
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.

Hitesh
  • 147
  • 2
  • 16
  • This works only if your objects are "simple". If your jsonrecord contains a datetime object or a bizarre object, what object.values will write. – Farandole Sep 22 '17 at 19:10
-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;
}