0

I have converted JSON to CSV using JavaScript but in a bizarre fashion, I don't see the headers being transferred to CSV file. I only see the corresponding values.

Below is the example of

1) JSON ....

[
 {
 "entityid": 2,
 "personid": 45676
 }
]

2) JavaScript code ....

function DownloadJSON2CSV(objArray)
 {
 alert(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]) {
 //line += array[i][index] + ',';
 if (line != '') line += ','
 line += array[i][index];
 }
 alert(line);
 // Here is an example where you would wrap the values in double quotes
 // for (var index in array[i]) {
 // line += '"' + array[i][index] + '",';
 // }
 //line.slice(0,line.Length-1); 
 str += line + '\r\n';
 }
 alert(str);
 window.open( "data:text/csv;charset=utf-8," + escape(str)) 
 }

3) CSV Output ....

2,45676


I should see the keys - entityid and personid also in CSV in the first line of the document, but I don't.

Apolo
4,0162 gold badges26 silver badges53 bronze badges
asked Jan 11, 2018 at 18:25
4
  • 1
    Which part of your code is responsible for including property keys into a string? Commented Jan 11, 2018 at 18:36
  • Guess this is the part where I am missing the keys - entityid, personid -----> for (var index in array[i]) { //line += array[i][index] + ','; if (line != '') line += ',' line += array[i][index]; } Commented Jan 11, 2018 at 19:16
  • As long as you absolutely sure that your JSON will always have flat and consistent structure, you just need to add index to the string. Commented Jan 11, 2018 at 19:19
  • Thanks for your reply. Yes my JSONs are going to be flat with no objects inside but I didn't get what you meant by add index to the string. Could you detail more please ? Commented Jan 11, 2018 at 19:35

2 Answers 2

1

This code will extract headers from the json keys additionally it will double quote the fields which include commas in it.

function convertToCSV(objArray) {
 var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
 var str = '';
 var keys = [];
 for(var k in objArray[0]) keys.push(k);
 for (var i = 0; i < keys.length; i++)
 {
 if(i==keys.length-1){str=str+keys[i]+'\r\n'}
 else {str=str+keys[i]+','}
 }
 for (var i = 0; i < array.length; i++) {
 var line = '';
 for (var index in array[i]) {
 if (line != '') line += ','
 if(array[i][index].toString().includes(",") && typeof array[i][index] === 'string'){array[i][index]="\""+array[i][index]+"\""}
 line += array[i][index];
 }
 str += line + '\r\n';
 }
 return str;
 }

Usage: (for Node.js)

var fs = require('fs'); //**run** npm install fs **if not installed yet in cmd**
var arrayOfObjects = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"},{"id":89,"Title":"England"}];
fs.writeFile("./test.csv", convertToCSV(arrayOfObjects));

answered Jun 28, 2018 at 9:19
Sign up to request clarification or add additional context in comments.

Comments

0

You hadn't set it up to output the header line.

function DownloadJSON2CSV(objArray)
 {
 var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
 var str = '';
 var headers = new Array();
 for (var i = 0; i < array.length; i++) {
 var line = '';
 var data = array[i];
 for (var index in data) {
 headers.push(index);
 if (line != '') {
 line += ','
 }
 line += '"' + array[i][index] + '"';
 console.log('line: ' + line);
 }
 str += line + ((array.length>1) ? '\r\n' : '');
 line = '';
 }
 headers = ArrNoDupe(headers);
 console.log('headers: ' + headers);
 console.log('str: ' + str);
 str = headers + '\r\n' + str;
 console.log('final str: ' + str);
 window.open( "data:text/csv;charset=utf-8," + escape(str));
 }
 function ArrNoDupe(a) {
 var temp = {};
 for (var i = 0; i < a.length; i++)
 temp[a[i]] = true;
 var r = [];
 for (var k in temp)
 r.push(k);
 return r;
 }

CSV outputs like so...

entityid,personid

"2","45676"

answered Jan 11, 2018 at 19:36

5 Comments

Thank you @daddygames ... this works. I am figuring out how you added comma in the header between the entityid and personid ... thank you so much.
I would just extract headers from the first object in the array.
@PM77-1 the reason I did it this way was so that if objects have additional properties, the names of those additional properties can be added to the header as well. The trouble with this is making sure it comes out consistent between objects with varying properties. I didn't code for consistency in that manner.
@Esh when you append an array object to a string, the runtime automagically converts the array to a comma-separated string value
Oh gotcha. Was wondering how that's working, now it makes sense. Thank you.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.