如何使用Node.js将JSON数组转换为CSV?

我想转换具有值数组的json。 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", ] ] } 

现在我想把这个数据转换成。 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" 

请使用Node.js给我suggetions。

这样做你自己:

 '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!'); } }); 

使用库

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

一个使用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!'); } }); }); 

三个简单的步骤:阅读。 兑换。 写。

第1步:阅读。

如果您需要从文件中读取JSON(如您在文章中包含文件名response.json ),则需要使用Node.js FileSystem API :

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

注意:如果您愿意,可以使用fs.readFile()asynchronous读取文件,并在callback函数中执行转换。

第2步:转换。

无论您是从本地文件读取JSON还是从服务器读取JSON,都需要先使用JSON.parse方法将其parsing为普通的旧JavaScript对象:

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

然后在子数组和父数组上执行一系列连接:
然后在父数组上执行连接:

 /* 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! */ 

编辑:

虽然前面的代码肯定有效,但在子数组上使用.map.join是没有必要的。 正如@Relu演示的那样 ,父数组上的单个.join就足够了,因为JavaScript会自动将子数组转换为以逗号分隔的string,因为.join必须返回一个string并且不能包含任何子数组。 如果你想在你的代码中明确地表示你想用非逗号来连接子数组,你可以使用前面的方法。 除此以外:

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

在这里,我们可以看到转换在行动:

 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);