Sometimes, we want to convert CSV to JSON in Node.js.
In this article, we’ll look at how to convert CSV to JSON in Node.js.
How to convert CSV to JSON in Node.js?
To convert CSV to JSON in Node.js, we can use the csvtojson module.
To install it, we run
npm i csvtohjson
Then we use it by writing
const csv = require("csvtojson");
csv()
.fromStream(readableStream)
.subscribe((jsonObj) => {
console.log(jsonObj)
})
const csvToJson = async () => {
const jsonArray = await csv().fromFile(filePath);
}
to call fromStream with a readableStream to read the CSV data from the stream.
Then we call subscribe with a callback to get the JSON converted from the CSV with jsonObj.
Also, we can use csv().fromFile with a CSV filePath to convert the CSV file at filePath to a JSON object by returning a promise with the JSON object.
We then get the JSON result with await.
Conclusion
To convert CSV to JSON in Node.js, we can use the csvtojson module.