csv to json in javascript code example
Example 1: parse csv javascript
//Suppose you have a CSV file data.csv which contains the data:
//NAME,AGE
//Daffy Duck,24
//Bugs Bunny,22
const csv = require('csv-parser')
const fs = require('fs')
const results = [];
fs.createReadStream('data.csv')
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', () => console.log(results));
// [{ NAME: 'Daffy Duck', AGE: '24' },
// { NAME: 'Bugs Bunny', AGE: '22' } ]
Example 2: convert json to csv npm
const { Parser } = require('json2csv'); const fields = ['field1', 'field2', 'field3'];const opts = { fields }; try { const parser = new Parser(opts); const csv = parser.parse(myData); console.log(csv);} catch (err) { console.error(err);}