Created
September 19, 2013 15:27
-
-
Save shaundon/6625196 to your computer and use it in GitHub Desktop.
JSON to CSV converter.
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
function JsonToCsv(json) { | |
var csv = ''; | |
// Begin with the header row, using | |
// the keys as headings. | |
for (var key in json[0]) { | |
csv += key + ','; | |
} | |
// Cut off the trailing comma. | |
csv = csv.substring(0, csv.length-1); | |
// Line break. | |
csv += '\r\n'; | |
// Iterate through the rows. | |
for (var i=0; i<json.length; i++) { | |
var line = ''; | |
for (var key in json[i]) { | |
if (line != '') { | |
line += ','; | |
} | |
line += json[i][key]; | |
} | |
csv += line + '\r\n'; | |
} | |
return csv; | |
} | |
/* | |
Test conversion: | |
[ | |
{ | |
"Header 1": "Data 1", | |
"Header 2": "Data 2", | |
"Header 3": "Data 3" | |
}, | |
{ | |
"Header 1": "Data 4", | |
"Header 2": "Data 5", | |
"Header 3": "Data 6" | |
}, | |
{ | |
"Header 1": "Data 7", | |
"Header 2": "Data 8", | |
"Header 3": "Data 9" | |
} | |
] | |
becomes: | |
Header 1,Header 2,Header 3 | |
Data 1,Data 2,Data 3 | |
Data 4,Data 5,Data 6 | |
Data 7,Data 8,Data 9 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment