Search code examples
node.jsjsoncsvcsvtojson

Csvtojson module returning unwanted keys


First question here,

Im trying to get a JSON object from a csv file using csvtojson npm module.

Everything works except the JSON object that i get has object keys on it:

Expected result:

{
 {"key": "value",
  "other_key": "other_value"
 },
 {"key": "value",
  "other_key": "other_value"
 }
}

Obtained:

{
 1:{
   "key": "value",
   "other_key": "other_value
 },
 2:{
    "key": "value",
    "other_key": "other_value
 }
}

My code for creating the JSON object is as follows:

csv({delimiter:";" }).fromFile(csv_path+name_csv)

The csvfile is as follows:

TITLE;TITLE2;TITLE3;TITLE4;TITLE5
string;string;int;string;int
string;string;int;string;int

Solution

  • Consider this implementation:

    const csv = require('csvtojson')
    
    var csvStr = `TITLE;TITLE2;TITLE3;TITLE4;TITLE5
    string;string;int;string;int
    string;string;int;string;int`
    
    csv({
      delimiter:";"
    })
    .fromString(csvStr)
    .then((csvRow)=>{
        console.log(csvRow)
    })
    

    It outputs an array of objects:

    [ { TITLE: 'string', TITLE2: 'string', TITLE3: 'int', TITLE4: 'string', TITLE5: 'int' }, { TITLE: 'string', TITLE2: 'string', TITLE3: 'int', TITLE4: 'string', TITLE5: 'int' } ]