Introduction
This tutorial will help you to read JSON file content using Node.js. This tutorial uses readFile and readFileSync functions of the jsonfile module.
Requirements
The first requirement is to have node.js and npm installed on your system. If not already installed use below links.
For this tutorial, we are using
jsonfile npm module. So first you need to install
jsonfile module on your system
$ npm install jsonfile --save
Now, I am creating a dummy json file employee.json. You can use your own json file.
Filename: employee.json [ { "emp_id" : "101", "emp_name" : "Mike", "emp_addr" : "123 California, USA", "designation" : "Editor" }, { "emp_id" : "102", "emp_name" : "Jacob", "emp_addr" : "456 Log Angelis, USA", "designation" : "Chief Editor" } ]
Read JSON File with Nodejs – Option #1
In above step, I have created a sample JSON file. Now create ReadJsonFile.js and add following content. You need to change employee.json with your JSON file name.
Filename: ReadJsonFile.js var jsonFile = require('jsonfile') var fileName = 'employee.json' jsonFile.readFile(fileName, function(err, jsonData) { if (err) throw err; for (var i = 0; i < jsonData.length; ++i) { console.log("Emp ID: "+jsonData[i].emp_id); console.log("Emp Name: "+jsonData[i].emp_name); console.log("Emp Address: "+jsonData[i].emp_addr); console.log("Designation: "+jsonData[i].designation); console.log("----------------------------------"); } });
Now run the nodejs script using following command.
$ node ReadJsonFile.js Emp ID: 101 Emp Name: Mike Emp Address: 123 California, USA Designation: Editor ---------------------------------- Emp ID: 102 Emp Name: Jacob Emp Address: 456 Log Angelis, USA Designation: Chief Editor ----------------------------------
Read JSON File with Nodejs - Option #2
Alternatively, you can use
readFileSync function to read json file content. Create a ReadJsonFileSync.js file with following content. You can
read here about the differences of readFile and readFileSync function in Jode.js.
Filename: ReadJsonFileSync.js var jsonFile = require('jsonfile') var fileName = 'employee.json' var jsonData = jsonFile.readFileSync(fileName); for (var i = 0; i < jsonData.length; ++i) { console.log("Emp ID : "+jsonData[i].emp_id); console.log("Emp Name : "+jsonData[i].emp_name); console.log("Emp Address : "+jsonData[i].emp_addr); console.log("Designation : "+jsonData[i].designation); console.log("----------------------------------"); }
Now run the nodejs script using following command.
$ node ReadJsonFileSync.js Emp ID: 101 Emp Name: Mike Emp Address: 123 California, USA Designation: Editor ---------------------------------- Emp ID: 102 Emp Name: Jacob Emp Address: 456 Log Angelis, USA Designation: Chief Editor ----------------------------------
Thanks for Visit Here
Comments
Post a Comment