How to Parse a Json File in Node

As the popularity of json a data interchange format is increasing day by day due to its light weight characteristics its important to understand to how to parse the json file in node.js. let us Create file StudentDetails.json with data :

{

"Name" : "Mohit",
"Roll No"
: "1899",
"Branch"
: "IT",
"Course"
: "B.tech"
}

Now let us try to read this File using readFileSync method, Create a ReadFileSync.js with the code:

var fs = require("fs");

var data = fs.readFileSync("StudentDetails.json", "UTF-8");
console.log(data);

Now run this  using our node.js command tool :

Image1.jpg

As we read the file we can see the content of the file but write now it is taking as “string” but in order to access the properties we need to convert it into an object for that we need to parse the value. To parse the value open your ReadFileSync.js in notepad and add the code

var fs = require("fs");

var data = fs.readFileSync("StudentDetails.json", "UTF-8");
console.log(data);

var
student = JSON.parse(data);

console.log("Student Name:" + student.Name);

let us run this with node.js command prompt

Image2.jpg

So we can access the properties values by just adding two lines of code JSON.parse(Content) is used to parse the file and we can access the values

Ebook Download
View all
Learn
View all