Skip to content

Instantly share code, notes, and snippets.

@Sikwan
Created December 18, 2012 10:30
Show Gist options
  • Save Sikwan/4326948 to your computer and use it in GitHub Desktop.
Save Sikwan/4326948 to your computer and use it in GitHub Desktop.
Allow the browser to transform a JSON to CSV and Download it. Base version from : http://www.zachhunter.com/2010/11/download-json-to-csv-using-javascript/
function Json2CSV(objArray)
{
var
getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys.join();
}, objArray = format_json(objArray)
, array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray
, 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';
}
str = getKeys(objArray[0]) + '\r\n' + str;
var a = document.createElement('a');
var blob = new Blob([str], {'type':'application\/octet-stream'});
a.href = window.URL.createObjectURL(blob);
a.download = 'export.csv';
a.click();
return true;
}
@ivadenis
Copy link

ivadenis commented Jan 8, 2014

where is format_json method?

@raghavj1991
Copy link

exactly

@timothyjoh
Copy link

The format_json was missing, but is not needed, Below I am posting the fixed version.

@timothyjoh
Copy link

function Json2CSV(objArray)
{
var
getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys.join();
}, array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray
, 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';
  }

  str = getKeys(objArray[0]) + '\r\n' + str;

  var a = document.createElement('a');
  var blob = new Blob([str], {'type':'application\/octet-stream'});
  a.href = window.URL.createObjectURL(blob);
  a.download = 'export.csv';
  a.click();
  return true;
}

// Usage
fake = [{'First Name':'Timothy', 'Last Name':'Johnson', 'Company':'Scitent'},{'First Name':'Eric', 'Last Name':'Glassman', 'Company':'Scitent'},{'First Name':'Mark', 'Last Name':'Cuban', 'Company':'SharkTank'},{'First Name':'Jeff', 'Last Name':'Bezos', 'Company':'Amazon'}];

Json2CSV(fake);

@strizzwald
Copy link

FYI, the serialization from JSON to CSV also includes the $$hashKey in the CSV. Was this intentional?

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