Search code examples
javascriptnpmdata-conversioncsvtojson

How do I convert a csv to json with npm's csvtojson and ignore the first row in the csv?


I have a csv as such:

this is the first column, this is the 2nd,
firstVal,                 secondVal
david,                    baseball
jon,                      soccer

I want to convert this to:

[{firstVal:david, secondVal:baseball},{firstVal:jon,secondVal:soccer}]

My first row in my csv is metadata (basically just a description of the actual column headers--firstVal and secondVal) that I don't want to be included in the json. I've tried:

csvtojson({noheader: true}).fromFile(csvFilePath)//...

but this doesn't seem to work. How can I do this conversion ignoring the first row?


Solution

  • My first row in my csv is metadata

    Then the problem is with your CSV. Which is fine. You can still use it, but you can't expect a library to have the tools you'll need to account for this strange use case.

    I think what makes the most sense is to read in the contents of the csv as a string and remove the first line before feeding it in to csvtojson. For that, I will borrow from this answer:

    csvStr = csvStr.substring(csvStr.indexOf("\n") + 1);
    

    Then you hand that over to csvtojson:

    csv().fromString(csvStr)