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
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
Share
Improve this question
asked Mar 13, 2013 at 9:36
FarandoleFarandole
5512 gold badges8 silver badges24 bronze badges
2
- possible duplicate of How to convert JSON to CSV format and store in a variable – jcubic Commented Mar 13, 2013 at 9:39
- 1 In my function, I have added header and dateformat are supported – Farandole Commented Mar 13, 2013 at 9:45
3 Answers
Reset to default 5Example in JSFiddle : http://jsfiddle/FLR4v/
Dependencies :
- Underscorejs http://underscorejs/underscore-min.js
- Momentjs http://cdnjs.cloudflare./ajax/libs/moment.js/2.0.0/moment.min.js
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;
}