How to Convert CSV File to JSON File in Node.js Using CSVTOJSON Library Full Example

How to Convert CSV File to JSON File in Node.js Using CSVTOJSON Library Full Example

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.

 

 

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.

 

name,age,subject
gautam,23,computer
pooja,23,maths
sanjay,25,hindi
shubham,29,social

 

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.

See also  Build a Sudoku Board Solver Puzzle Game in HTML5 CSS3 and Javascript Full Project For Beginners

 

[
  { "name": "gautam", "age": "23", "subject": "computer" },
  { "name": "pooja", "age": "23", "subject": "maths" },
  { "name": "sanjay", "age": "25", "subject": "hindi" },
  { "name": "shubham", "age": "29", "subject": "social" }
]

Leave a Reply