Welcome folks today in this blog post we will be converting csv to json
file using csvtojson
library in node.js using javascript. All the full source code of the application is shown below.
Get Started
In order to get started you need to install the below library
using the below command as shown below
npm i csvtojson
And now we need to make the index.js
file and copy paste the following code
index.js
1 2 |
const csvToJson = require('csvtojson'); const fs = require('fs') |
As you can see at the very top we are importing
the csvtojson
module and also we are importing the fs
module. And now we need to create the data.csv
file and copy paste the same csv code as shown below
1 2 3 4 5 6 |
csvToJson().fromFile('data.csv').then(jsonObj => { // Print the JSON object to the console console.log(jsonObj); fs.writeFileSync("result.json",JSON.stringify(jsonObj)) }); |
As you can see that we are calling the csvToJson()
module and inside it we are calling the fromFile()
method to load the input csv
file called data.csv
and then we are converting the csv
file to an array of json
objects. And it returns the promise we are handling that using the then
statement and inside it we are saving
the result as json
file using the fs
module. We are using the JSON.stringify()
method to convert javascript objects to json
strings as shown below
Full Source Code
1 2 3 4 5 6 7 8 9 |
const csvToJson = require('csvtojson'); const fs = require('fs') csvToJson().fromFile('data.csv').then(jsonObj => { // Print the JSON object to the console console.log(jsonObj); fs.writeFileSync("result.json",JSON.stringify(jsonObj)) }); |