Skip to content

Instantly share code, notes, and snippets.

@dannypule
Created February 8, 2017 18:40
Show Gist options
  • Star 31 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save dannypule/48418b4cd8223104c6c92e3016fc0f61 to your computer and use it in GitHub Desktop.
Save dannypule/48418b4cd8223104c6c92e3016fc0f61 to your computer and use it in GitHub Desktop.
Export JSON to CSV file using Javascript
function convertToCSV(objArray) {
var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
var str = '';
for (var i = 0; i < array.length; i++) {
var line = '';
for (var index in array[i]) {
if (line != '') line += ','
line += array[i][index];
}
str += line + '\r\n';
}
return str;
}
function exportCSVFile(headers, items, fileTitle) {
if (headers) {
items.unshift(headers);
}
// Convert Object to JSON
var jsonObject = JSON.stringify(items);
var csv = this.convertToCSV(jsonObject);
var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", exportedFilenmae);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}
var headers = {
model: 'Phone Model'.replace(/,/g, ''), // remove commas to avoid errors
chargers: "Chargers",
cases: "Cases",
earphones: "Earphones"
};
itemsNotFormatted = [
{
model: 'Samsung S7',
chargers: '55',
cases: '56',
earphones: '57',
scratched: '2'
},
{
model: 'Pixel XL',
chargers: '77',
cases: '78',
earphones: '79',
scratched: '4'
},
{
model: 'iPhone 7',
chargers: '88',
cases: '89',
earphones: '90',
scratched: '6'
}
];
var itemsFormatted = [];
// format the data
itemsNotFormatted.forEach((item) => {
itemsFormatted.push({
model: item.model.replace(/,/g, ''), // remove commas to avoid errors,
chargers: item.chargers,
cases: item.cases,
earphones: item.earphones
});
});
var fileTitle = 'orders'; // or 'my-unique-title'
exportCSVFile(headers, itemsFormatted, fileTitle); // call the exportCSVFile() function to process the JSON and trigger the download
@easyWLP
Copy link

easyWLP commented Jul 29, 2018

S:\FTP\uniPaaS\WL\RKSV\DEP-Prueftool\regkassen-verification-1.1.1\Pueftool_Ergebnisse\DEP-full.json

@blak-code-tech
Copy link

Good Job!!

@ThisTemba
Copy link

If anyone is using this code, consider changing line 10 to: line += '"' + array[i][index] + '"';
If you have strings with commas in them, this will prevent the commas in the strings from splitting the content into different cells.
See this post: https://stackoverflow.com/a/4617967/3593621

@meilechwieder
Copy link

FileName will allways be undefined.csv
Here's a fix:

  var exportedFilenmae = (fileTitle || "export") + ".csv" ;

@PSanilP
Copy link

PSanilP commented Aug 6, 2023

Can remove headers as input by doing this
exportCSVFile: function (jArray, fileName) { jArray.unshift(Object.keys(jArray[0]));

@PSanilP
Copy link

PSanilP commented Aug 6, 2023

minified
jArrayToCSV: function (d) { var c = typeof d != 'object' ? JSON.parse(d) : d; var e = ''; for (var a = 0; a < c.length; a++) { var b = ''; for (var f in c[a]) b != '' && (b += ','), b += '"' + c[a][f] + '"'; e += b + '\r\n'; } return e; }, exportCSVFile: function (jArray, fileName) { jArray.unshift(Object.keys(jArray[0])); var f = JSON.stringify(jArray); var g = this.jArrayToCSV(f); var b = (fileName || 'export') + '.csv'; var c = new Blob([g], { type: 'text/csv;charset=utf-8;' }); if (navigator.msSaveBlob) navigator.msSaveBlob(c, b); else { var a = document.createElement('a'); if (a.download !== undefined) { var h = URL.createObjectURL(c); a.setAttribute('href', h), a.setAttribute('download', b), a.style.visibility = 'hidden', document.body.appendChild(a), a.click(), document.body.removeChild(a); } } }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment