Search code examples
node.jsjsoncsvcsvtojson

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.

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 (#):

# 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:

enter image description here

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.


Solution

  • You can try replacing the lines before parsing (not tested) :

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