Last active
June 7, 2016 07:18
-
-
Save aqiank/36f43793882f787ae06ab9ef0f150f69 to your computer and use it in GitHub Desktop.
Simple JavaScript to convert JSON to CSV
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(data) { | |
if (typeof(data) != 'object') { | |
if (typeof(data) != 'string') { | |
console.error('Error: data is not a JavaScript object or a string'); | |
return null; | |
} | |
try { | |
data = JSON.parse(data); | |
} catch (error) { | |
console.error('Error: ' + error); | |
return null; | |
} | |
} | |
// Check whether the data is not an array | |
if (!(data.hasOwnProperty('length') && typeof(data.length) == 'number')) { | |
console.error('Error: data is not an array'); | |
return null; | |
} | |
// Check whether the data has any elements in it | |
if (data.length == 0) { | |
console.error('Error: data has zero elements'); | |
return ''; | |
} | |
var output = ''; | |
var columns = Object.keys(data[0]); | |
// Write the columns | |
for (var i = 0; i < columns.length; i++) { | |
output += '"' + columns[i] + '",'; | |
} | |
output += '\n'; | |
// Write the data | |
for (var i = 0; i < data.length; i++) { | |
for (var j = 0; j < columns.length; j++) { | |
output += '"' + data[i][columns[j]] + '",'; | |
} | |
output += '\n'; | |
} | |
return output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment