Last active
August 29, 2015 14:14
-
-
Save pradeepn/40a3f0d4071028f6db44 to your computer and use it in GitHub Desktop.
JSON to CSV string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 || ','; | |
console.log(jsonArray); | |
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 for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment