如何在Node.js中将CSV转换为JSON

93
我正试图将csv文件转换为json。我正在使用的是。
示例CSV:
a,b,c,d
1,2,3,4
5,6,7,8
...

期望的 JSON:

{"a": 1,"b": 2,"c": 3,"d": 4},
{"a": 5,"b": 6,"c": 7,"d": 8},
...

我尝试使用node-csv解析库,但输出结果像数组而不是我期望的形式。

我正在使用Node 0.8和express.js,并希望获得一个简单的建议来完成这个任务。


http://apievangelist.com/2013/09/24/excel-and-csv-conversion-to-json-and-xml-in-javascript-that-runs-100-on-github/ 和 http://kinlane.github.io/csv-converter/ 看起来很不错。 - VonC
我写了一篇小博客,介绍了与brnrd提出的类似解决方案:http://thinkingonthinking.com/scripting-a-csv-converter/ - poseid
21个回答

1
Step 1:
安装 Node 模块: npm install csvtojson --save Step 2:
var Converter = require("csvtojson").Converter;

var converter = new Converter({});

converter.fromFile("./path-to-your-file.csv",function(err,result){

    if(err){
        console.log("Error");
        console.log(err);  
    } 
    var data = result;

    //to check json
    console.log(data);
});

1

Node-ETL 包足以处理所有的BI数据处理。

npm install node-etl; 

然后:

var ETL=require('node-etl');
var output=ETL.extract('./data.csv',{
              headers:["a","b","c","d"],
              ignore:(line,index)=>index!==0, //ignore first line
 });

这个库的链接已经失效了 - 或许它已经被移动到 Github 的其他位置(或者被 fork 了)?请更新链接。 - Max
感谢@RohitParte。这是我在NodeJs中的第一个模块之一。虽然某些功能运行良好,但它缺少许多功能。我变得非常忙碌,从事其他事情(可靠性工程,DevOps等)。 - Abdennour TOUMI

1

2023答案 - 适用于带有字段内换行和字段内分隔符(逗号)的CSV文件

我决定为以下原因编写自己的函数:

  • csvtojson从2021年6月7日以来没有更新,其中包含对已弃用且可能在受限环境中失败的substr的调用。
  • 答案中提供的纯JS函数无法处理我的数据集,因为它包含既有逗号又有换行符的字段,这两种情况都得到了RFC 4180的支持。
  • 更新:我意识到我的数据集还包含一个字段中的双引号,如果使用另一个双引号进行转义,则是有效的,因此我也更新了我的答案以考虑这一点。 有效双引号的示例:"Name ""Nickname"" LastName"
import fs from "fs";

function readCSV(filepath, separator = ",") {
  /** Reads a csv file, taking into consideration linebreaks inside of fields, and double quotes or no quotes.
   * Converts it into a json object
   */
  const fp = new URL(filepath, import.meta.url);
  const file = fs.readFileSync(fp, { encoding: "utf-8" });

  // Figure out how many cells there are by counting the first line. 
  // ATTENTION: If your header contains commas or a linebreak, this will fail.
  const firstLineBreak = file.indexOf("\n");
  const rowsNum = file.slice(0, firstLineBreak).split(",").length;

  // Construct a regex based on how many headers there are
  const singleCellRegex = `(?:(?:"([\\s\\S]*?)")|((?:(?:[^"${separator}\\n])|(?:""))+))`;
  let regexText = "";

  for (let i = 0; i < rowsNum; i++) {
    regexText += "," + singleCellRegex;
  }

  const regex = new RegExp(regexText.slice(1), "g");
  const results = file.matchAll(regex);

  const rowsArr = [];
  for (const row of results) {
    const newRow = [];

    for (let i = 0; i < rowsNum; i++) {
      const rowValue = row[2 * i + 1] ?? row[2 * i + 2];
      newRow.push(rowValue.replaceAll('""', '"')); // Remove double double quotes
    }

    rowsArr.push(newRow);
  }

  const headers = rowsArr[0];
  const rows = rowsArr.slice(1);

  return rows.map((row) =>
    row.reduce((jsonRow, field, idx) => {
      jsonRow[headers[idx]] = field;
      return jsonRow;
    }, {})
  );
}

1

npm install csvjson --save
在你的 Node JS 文件中

const csvjson = require('csvjson');
convertCSVToJSON(*.csv);

convertCSVToJSON = (file) => {
  const convertedObj = csvjson.toObject(file);
}


1
我使用了csvtojson库将csv字符串转换为json数组。 该库有多种功能可帮助您转换为JSON。
它还支持从文件和文件流中读取。 在解析可能包含逗号(,)或任何其他分隔符的csv时要小心。 要删除分隔符,请参见我的答案here

0
在我的情况下,JSON.stringify没有帮助,因为文件太大了。 这个方法解决了我的需求:
let csvFile = fs.readFileSync(
  csvFilePath,
  { encoding: "utf-8" },
  function (err) {
    console.log(err);
  }
);
csvFile = csvFile.split("\n");

let strFile = "export default [";
csvFile.forEach(function (d) {
  let row = d.split(",");
  strFile += `[${row}],`;
});
strFile += "]";

0

我通过安装csvtojson模块并使用以下代码将一个大型(315 MB)的csv文件转换为json:

const fs = require('fs')
const Converter = require('csvtojson').Converter
const csvConverter = new Converter({
    constructResult:false,
    downstreamFormat:"array",
})

csvConverter.subscribe=function(json,row,index){
    json["rowIndex"]=index
};

const readStream = fs.createReadStream('./data.csv') // my csv file
const writeStream = fs.createWriteStream('./data.json') // my new json file

readStream.pipe(csvConverter).pipe(writeStream)

生成的 JSON 文件格式符合要求:

[
{"a": 1,"b": 2,"c": 3,"d": 4},
{"a": 5,"b": 6,"c": 7,"d": 8},
]

0

csvtojson模块是一个全面的nodejs csv解析器,可将csv转换为json或列数组。它可以作为node.js库/命令行工具/或在浏览器中使用。以下是一些特点:

/** csv file
a,b,c
1,2,3
4,5,6
*/
const csvFilePath='<path to csv file>'
const csv=require('csvtojson')
csv()
.fromFile(csvFilePath)
.then((jsonObj)=>{
    console.log(jsonObj);
    /**
     * [
     *  {a:"1", b:"2", c:"3"},
     *  {a:"4", b:"5". c:"6"}
     * ]
     */ 
})
 
// Async / await usage
const jsonArray=await csv().fromFile(csvFilePath);

0
我和我的伙伴创建了一个网络服务来处理这种事情。
请查看Modifly.co,了解如何通过单个RESTful调用将CSV转换为JSON的说明。

0

一旦弄清楚如何将csv数据转换为二维数组:

[['header1','header2'],['data1','data2']]

转换为json只需使用map和reduce即可:

const keys = input[0]
const jsonOutput = input.slice(1)
  .map(arr2 => keys.reduce((accumulator, element, index) => {
    return { ...accumulator,
      [element]: arr2[index]
    };
  }, {}))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接