Skip to content

Instantly share code, notes, and snippets.

@puneetar
Created September 8, 2016 20:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save puneetar/805b93363d472385381b69db66530748 to your computer and use it in GitHub Desktop.
Save puneetar/805b93363d472385381b69db66530748 to your computer and use it in GitHub Desktop.
Javascript function to convert JSON to CSV
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