To convert CSV to JSON in our Node.js apps, we can use the csvtojson
library.
To install it, we run:
npm i csvtojson
Then we if have the following in sample.csv
:
a,b,c,d
1,2,3,4
5,6,7,8
then we can convert the CSV file content into a JSON object by writing:
const csv = require("csvtojson");
const csvFilePath = './sample.csv'
const convertToJson = async (csvFilePath) => {
const jsonArrayObj = await csv().fromFile(csvFilePath)
console.log(jsonArrayObj);
}
convertToJson(csvFilePath)
We have the convertToJson
function that takes a csvFilePath
.
Then we call csv().fromFile
with it to convert the CSV file content into a JSON object and assign that to jsonArrayObj
.
As a result, jsonArrayObj
is:
[
{ a: '1', b: '2', c: '3', d: '4' },
{ a: '5', b: '6', c: '7', d: '8' }
]
when we call it.