Last active
October 13, 2015 00:58
-
-
Save michelle/4114518 to your computer and use it in GitHub Desktop.
Converts an array of JSON objects to a CSV string, with a header (assuming complete objects as from a database). Does not use Object.keys.
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
// Converts an array of JSON objects a CSV string. | |
function JSONtoCSV(jsonArray) { | |
var csv = ''; | |
var header = ''; | |
for (var i = 0; i < jsonArray.length; i += 1) { | |
var entry = ''; | |
var obj = jsonArray[i]; | |
for (var property in obj) { | |
if (obj.hasOwnProperty(property)) { | |
// Create header. | |
if (i == 0) { | |
if (header != '') header += ',' | |
header += property | |
} | |
// Comma-split unless line is empty. | |
if (entry != '') entry += ',' | |
entry += jsonArray[i][property]; | |
} | |
} | |
csv += entry + '\r\n'; | |
} | |
csv = header + '\r\n' + csv; | |
return csv; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment