Welcome folks today in this post we will be talking about how to covert a simple csv file to json file in node.js using csvtojson library tutorial for beginners. All the source code is given in the description. A step by step youtube video is also shown below.
1 2 3 4 |
const csvtojson = require('csvtojson') const fs = require('fs') const csvfilepath = "simple.csv" |
First of all we are importing all the libraries that we will need for this project. First one is the csvtojson,fs,and then we are providing a filename for the input csv file. This we have created in the same folder.The contents of the input.csv file are as follows.
1 2 3 4 5 |
name,age,subject gautam,23,computer pooja,23,maths sanjay,25,hindi shubham,29,social |
1 2 3 4 5 6 7 8 9 |
csvtojson() .fromFile(csvfilepath) .then((json) => { console.log(json) fs.writeFileSync("output.json",JSON.stringify(json),"utf-8",(err) => { if(err) console.log(err) }) }) |
Now we will call the library function to take input from file and convert it to json. After that we create a new file in the root directory with the help of writeFileSync output.json file. If you execute this node script after that you will find a output.json file which will contain the following contents.
1 2 3 4 5 6 |
[ { "name": "gautam", "age": "23", "subject": "computer" }, { "name": "pooja", "age": "23", "subject": "maths" }, { "name": "sanjay", "age": "25", "subject": "hindi" }, { "name": "shubham", "age": "29", "subject": "social" } ] |