How to convert JSON array to CSV using Node.js?

匿名 (未验证) 提交于 2019-12-03 07:50:05

问题:

I want to convert json which has value array. response.json

{ "rows": [ [   "New Visitor",   "(not set)",   "(not set)",         "0" ], [   "New Visitor",   "(not set)",   "(not set)",   "mobile"       ], [   "New Visitor",   "(not set)",   "(not set)",   "mobile"     ],   [     "New Visitor",     "(not set)",     "(not set)",    "mobile",         ]  ] } 

Now i want to convert this data into. name.csv

 "New Visitor","(not set)","(not set)","0"  "New Visitor","(not set)","(not set)","mobile"          "New Visitor","(not set)","(not set)","mobile"      "New Visitor","(not set)","(not set)","mobile" 

Please give me suggetions using Node.js.

回答1:

Do it yourself like this:

'use strict';  var stringify = require('csv-stringify'); var fs = require('fs');  let myObj = {   "rows": [     [       "New , Visitor",       "(not set)",       "(not set)",       "0"     ],     [       "New Visitor",       "(not set)",       "(not set)",       "mobile"     ],     [       "New Visitor",       "(not set)",       "(not set)",       "mobile"     ],     [       "New Visitor",       "(not set)",       "(not set)",       "mobile",     ]   ] }  // 1. One way - if you want the results to be in double quotes and you have comas inside  // choose another string to temporally replace commas if necessary let stringToReplaceComas = '!!!!';  myObj.rows.map((singleRow) => {   singleRow.map((value, index) => {     singleRow[index] = value.replace(/,/g, stringToReplaceComas);   }) })  let csv = `"${myObj.rows.join('"\n"').replace(/,/g, '","')}"`; // // or like this // let csv = `"${myObj.rows.join('"\n"').split(',').join('","')}"`;  csv = csv.replace(new RegExp(`${stringToReplaceComas}`, 'g'), ',');  // // 2. Another way - if you don't need the double quotes in the generated csv and you don't have comas in rows' values // let csv = myObj.rows.join('\n')  fs.writeFile('name.csv', csv, 'utf8', function(err) {   if (err) {     console.log('Some error occured - file either not saved or corrupted file saved.');   } else {     console.log('It\'s saved!');   } }); 

Use libraries

ex. https://github.com/wdavidw/node-csv, https://github.com/wdavidw/node-csv-stringify

an example using csv-stringify

'use strict';  var stringify = require('csv-stringify'); var fs = require('fs');  let myObj = {   "rows": [     [       "New Visitor",       "(not set)",       "(not set)",       "0"     ],     [       "New Visitor",       "(not set)",       "(not set)",       "mobile"     ],     [       "New Visitor",       "(not set)",       "(not set)",       "mobile"     ],     [       "New Visitor",       "(not set)",       "(not set)",       "mobile",     ]   ] }  stringify(myObj.rows, function(err, output) {   fs.writeFile('name.csv', output, 'utf8', function(err) {     if (err) {       console.log('Some error occured - file either not saved or corrupted file saved.');     } else {       console.log('It\'s saved!');     }   }); }); 


回答2:

Three easy steps: Read. Convert. Write.

Step 1: Read.

If you need to read the JSON from a file (as indicated by your inclusion of the filename response.json in your post), you will require the Node.js FileSystem API:

var fs = require('fs');                        // Require Node.js FileSystem API. var inJSON = fs.readFileSync('response.json'); // Read the file synchronously. 

Note: If you prefer, you can read the file asynchronously with fs.readFile() and perform the conversion in a callback function.

Step 2: Convert.

Whether you read your JSON from a local file or GET it from a server, you will need to parse it into a Plain Old JavaScript Object first using the JSON.parse method:

inJSON = JSON.parse(inJSON);  // Parse JSON into POJO. 

Then perform a series of joins on the child arrays and parent array:
Then perform a join on the parent array:

/* SEE EDIT BELOW var outCSV = inJSON.rows.map( // Map returns a new array.     (curr) => curr.join(',')  // Each child array becomes a comma-separated string. ).join('\n');                 // Parent array becomes a newline-separated string...                               // ...of comma-separated strings.                               // It is now a single CSV string! */ 

EDIT:

While the previous code certainly works, it is unnecessary to use .map and .join on the child arrays. As @Relu demonstrates, a single .join on the parent array is sufficient because JavaScript will automatically convert the child arrays into comma-separated strings by default since .join must return a string and cannot contain any child arrays. You could use the previous method if you wanted to be explicit in your code of if you wanted to join the child arrays with something other than a comma. Otherwise:

var outCSV = inJSON.rows.join('\n'); // Array becomes a newline-separated string...                                      // ...of comma-separated strings.                                      // It is now a single CSV string! 

Here, we can see that conversion in action:

var inJSON = {   "rows": [     [       "New Visitor",       "(not set)",       "(not set)",             "0"     ],     [       "New Visitor",       "(not set)",       "(not set)",       "mobile"           ],     [       "New Visitor",       "(not set)",       "(not set)",       "mobile"         ],     [       "New Visitor",       "(not set)",       "(not set)",       "mobile" // NOTE: Here I removed a trailing comma,                // ...which is invalid JSON!     ]   ] }  var outCSV = inJSON.rows.join('\n');  console.log(outCSV);

Step 3: Write.

Using the FileSystem API again, write to a file, and log an error or a success message:

fs.writeFile('name.csv', outCSV, function (err) {     if (err) {         return console.log(err);     }     console.log('FILE SUCCESSFULLY WRITTEN!\n'); }); 

Note: Here, I demonstrate the asynchronous pattern using a callback to log my error and success messages. If you prefer, you can write the file synchronously with fs.writeFileSync().

Putting it all together

I like to add plenty of console.log() messages to my Node.js scripts.

var fs = require('fs');  var inFilename  = 'response.json',     outFilename = 'name.csv';  console.log('\nPreparing to read from ' + inFilename + ' ...');  var inJSON = fs.readFileSync(inFilename);  console.log('READ:'); console.log(inJSON);  console.log('\nPreparing to parse as JSON ...');  inJSON = JSON.parse(inJSON);  console.log('PARSED:'); console.log(inJSON);  console.log('\nPreparing to convert into CSV ...');  var outCSV = inJSON.rows.join('\n');  console.log('CONVERTED:'); console.log(outCSV);  console.log('\nPreparing to write to ' + outFilename + '...'); fs.writeFile(outFilename, outCSV, function (err) {     if (err) {         return console.log(err);     }     console.log('FILE SUCCESSFULLY WRITTEN!\n'); });  


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!