简体   繁体   English

使用文档顶部的注释将 csv 转换为 JSON (Node.js)

[英]Convert csv to JSON with comments at the top of document (Node.js)

I'm using csvtojson library in NodeJS to convert csv file to JSON.我在 NodeJS 中使用 csvtojson 库将 csv 文件转换为 JSON。

var csv = require("csvtojson");

async function convert() {
    const jsonArray=await csv({delimiter:[";"]}).fromFile("file.csv");
    console.log(jsonArray);
}

The problem is that first two lines in my csv files contain comments (#):问题是我的 csv 文件中的前两行包含注释 (#):

# Version 1.00
#
freq[Hz];re:Trc1_S11;im:Trc1_S11;re:Trc2_S21;im:Trc2_S21;
2.400000000000000E+009;1.508471667766571E-001;1.125726923346520E-001;1.501466613262892E-004;-3.452933859080076E-003;
2.400166666666667E+009;1.506395637989044E-001;1.104702129960060E-001;1.065352989826351E-004;-3.356512635946274E-003;
2.400333333333334E+009;1.510340869426727E-001;1.083744764328003E-001;8.569851343054324E-005;-3.419617656618357E-003;
2.400500000000000E+009;1.511266380548477E-001;1.056981831789017E-001;7.480625936295837E-005;-3.567710286006331E-003;

Returned JSON is corrupted because of first two lines:由于前两行,返回的 JSON 已损坏:

在此处输入图片说明

Is there a way to skip/ignore these commented lines?有没有办法跳过/忽略这些注释行? I have a lot ov csv files and each has comments in first two lines.我有很多 ov csv 文件,每个文件的前两行都有注释。

You can try replacing the lines before parsing (not tested) :您可以尝试在解析之前替换行(未测试):

const jsonArray = await csv({delimiter:[";"]}).fromFile("file.csv")
                          .preRawData(csvRawData => csvRawData.replace(/^#.*\n/gm, ''));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM