How to Parse a Json File in Node

Introduction

 
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:
  1.  var fs = require("fs");  
  2. var data = fs.readFileSync("StudentDetails.json""UTF-8");  
  3.    
  4. 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
  1.  var fs = require("fs");  
  2. var data = fs.readFileSync("StudentDetails.json""UTF-8");  
  3.    
  4. console.log(data);  
  5.    
  6. var student = JSON.parse(data);  
  7.    
  8. 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