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

新手上路,请多包涵

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

现在我想把这些数据转换成。 名称.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 的建议。

原文由 arjun kori 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
2 个回答

像这样自己做:

 '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-csv , https://github.com/wdavidw/node-csv , https://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', 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!');
      }
    });
};

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

原文由 Relu Mesaros 发布,翻译遵循 CC BY-SA 4.0 许可协议

三个简单的步骤:阅读。转变。写。

第一步:阅读。

如果您需要从文件中读取 JSON(如您在帖子中包含的文件名 response.json ),您将需要 Node.js 文件系统 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.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 所演示 的,父数组上的单个 .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);

第三步:写。

再次使用 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(`Preparing to read from ${inFilename} …`);

const JSONContents = fs.readFileSync(inFilename);

console.log(`READ:\n${JSONContents}`);
console.log('Preparing to parse as JSON …');

const JSONasPOJO = JSON.parse(JSONContents);

console.log(`PARSED:\n${JSONasPOJO}`);
console.log('Preparing to convert into CSV …');

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

console.log(`CONVERTED:\n${CSVString}`);
console.log(`Preparing to write to ${outFilename} …`);

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

原文由 gfullam 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题