Created
September 8, 2016 20:14
-
-
Save puneetar/805b93363d472385381b69db66530748 to your computer and use it in GitHub Desktop.
Javascript function 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
export function JSONToCSVConvertor(JSONData, fileName, ShowLabel, errorCallback) { | |
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData; | |
var CSV = ''; | |
if (ShowLabel) { //This condition will generate the Label/Header | |
var row = ""; | |
for (var index in arrData[0]) { //This loop will extract the label from 1st index of on array | |
if (arrData[0].hasOwnProperty(index)) { | |
row += index + ','; //Now convert each value to string and comma-seprated | |
} | |
} | |
row = row.slice(0, -1); | |
CSV += row + '\r\n'; //append Label row with line break | |
} | |
for (var i = 0; i < arrData.length; i++) { //1st loop is to extract each row | |
var row_1 = ""; | |
for (var index_1 in arrData[i]) { | |
if (arrData[i].hasOwnProperty(index_1)) { | |
row_1 += '"' + arrData[i][index_1] + '",'; | |
} | |
} | |
row_1.slice(0, row_1.length - 1); | |
CSV += row_1 + '\r\n'; //add a line break after each row | |
} | |
if (CSV == '') { | |
errorCallback("Invalid data"); | |
} | |
var link = (function () { //this will generate a temp "a" tag | |
var l = document.createElement("a"); | |
l.id = "lnkDwnldLnk"; | |
document.body.appendChild(l); | |
return $("#lnkDwnldLnk"); | |
}()); | |
function createObjectURL(file) { | |
if (window.URL && window.URL.createObjectURL) { | |
return window.URL.createObjectURL(file); | |
} else if (window.webkitURL) { | |
return window.webkitURL.createObjectURL(file); | |
} else { | |
errorCallback("CreateObjectURL not supported by the browser"); | |
} | |
} | |
var blob = new Blob([CSV], {type: 'text/csv'}); | |
var csvUrl = createObjectURL(blob); | |
var filename = fileName + '.csv'; | |
link.attr({ | |
'download': filename, | |
'href': csvUrl | |
}); | |
link[0].click(); | |
link.remove(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment