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
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;
}
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.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.