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

时间:2016-07-07 11:27:32

标签: json node.js csv express

我想转换有值数组的json。 的 response.json

 "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

0

请使用Node.js给我建议。

4 个答案:

答案 0 :(得分:16)

自己这样做:

'use strict';

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/mrodrig/json-2-csvhttps://github.com/wdavidw/node-csvhttps://github.com/wdavidw/node-csv-stringify

使用json-2-csv(https://github.com/mrodrig/json-2-csv

的示例
'use strict';

const converter = require('json-2-csv');

let myObj = {
  "rows": [
    {
      value1: "New Visitor",
      value2: "(not set)",
      value3: "(not set)",
      value4: "0"
    },
    {
      value1: "New Visitor",
      value2: "(not set)",
      value3: "(not set)",
      value4: "mobile"
    },
    {
      value1: "New Visitor",
      value2: "(not set)",
      value3: "(not set)",
      value4: "mobile"
    },
    {
      value1: "New Visitor",
      value2: "(not set)",
      value3: "(not set)",
      value4: "mobile",
    }
  ]
}

let json2csvCallback = function (err, csv) {
    if (err) throw err;
    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!');
      }
    });
};

converter.json2csv(myObj.rows, json2csvCallback, {
  prependHeader: false      // removes the generated header of "value1,value2,value3,value4" (in case you don't want it)
});

使用csv-stringify(https://github.com/wdavidw/node-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 :(得分:5)

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

第1步:阅读。

如果您需要从文件中读取JSON(如您在帖子中包含文件名response.json所示),则需要Node.js FileSystem API

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

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

第2步:转换。

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

const JSONasPOJO = JSON.parse(JSONFile); // Parse JSON into POJO.

然后对子数组和父数组执行一系列连接:
参见编辑以下

/* THIS IS UNNECESSARY FOR "COMMA" SEPARATED VALUES
const CSVString = JSONasPOJO
    .rows                    // Get `rows`, which is an array.
    .map(                    // Map returns a new array.
        row => row.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 demonstrates,父数组上的单个.join就足够了,因为JavaScript会自动将子数组转换为逗号分隔的字符串,因为.join必须返回一个字符串且不能包含任何子字符串阵列。

如果要使用逗号以外的其他内容连接子数组,可以使用上一个方法。

否则:

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

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



const JSONasPOJO = {
  "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!
    ]
  ]
}

const CSVString = JSONasPOJO.rows.join('\n');

console.log(CSVString);




第3步:写。

再次使用FileSystem API,写入文件,并记录错误或成功消息:

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

注意:在这里,我使用回调来演示异步模式,以记录我的错误和成功消息。如果您愿意,可以与fs.writeFileSync()同步编写文件。

全部放在一起

我想在我的Node.js脚本中添加大量console.log()消息。

const fs = require('fs');

const inFilename  = 'response.json',
      outFilename = 'name.csv';

console.log('\nPreparing to read from ' + inFilename + ' ...');

const JSONContents = fs.readFileSync(inFilename);

console.log('READ:');
console.log(JSONContents);

console.log('\nPreparing to parse as JSON ...');

const JSONasPOJO = JSON.parse(JSONContents);

console.log('PARSED:');
console.log(JSONasPOJO);

console.log('\nPreparing to convert into CSV ...');

const CSVString = JSONasPOJO.rows.join('\n');

console.log('CONVERTED:');
console.log(CSVString);

console.log('\nPreparing to write to ' + outFilename + '...');

fs.writeFile(outFilename, CSVString, err => {
    if (err) return console.log(err);
    console.log('FILE SUCCESSFULLY WRITTEN!\n');
});

答案 2 :(得分:0)

我对你们不了解,但是我喜欢可以按预期工作且无需进行大量额外配置的小程序包,请尝试使用jsonexport,我认为这是最好的模块,它与对象,数组, ..及其快速!

安装

npm i --save jsonexport

用法

const jsonexport = require('jsonexport');
const fs = require('fs');

jsonexport([{
  value1: "New Visitor",
  value2: "(not set)",
  value3: "(not set)",
  value4: "0"
},
{
  value1: "New Visitor",
  value2: "(not set)",
  value3: "(not set)",
  value4: "mobile"
},
{
  value1: "New Visitor",
  value2: "(not set)",
  value3: "(not set)",
  value4: "mobile"
},
{
  value1: "New Visitor",
  value2: "(not set)",
  value3: "(not set)",
  value4: "mobile",
}], function(err, csv) {
  if (err) return console.error(err);
  fs.writeFile('output.csv', csv, function(err) {
    if (err) return console.error(err);
    console.log('output.csv saved');
  });
});

https://github.com/kauegimenes/jsonexport

答案 3 :(得分:-1)

我想分享从json数组构建csv字符串的最简单方法:

const data = [
  { a: 1, b: new Date(), c: 'a text' },
  {
    a: 1, b: new Date(), c: `string
  with
  return
  carrier
  and emoji ?
  `
  }
]

const header = Object.keys(data[0]).map(_ => JSON.stringify(_)).join(';') + '\n'
const outData = data.reduce((acc, row) => {
  return acc + Object.values(row).map(_ => JSON.stringify(_)).join(';') + '\n'
}, header)

console.log(outData)

将打印此字符串:

"a";"b";"c"
1;"2020-03-25T08:49:04.280Z";"a text"
1;"2020-03-25T08:49:04.280Z";"string\n  with\n  return\n  carrier\n  and emoji ?\n  "