How to Get Data from Json File in Node JS?

By Hardik Savani May 28, 2021 Category : Node JS

Hello,

Now, let's see post of how to get data from json file in node js. you will learn how to fetch data from json in node js. This article goes in detailed on how to get value from json object in node js. you will learn node js read json file example.

In this post, i will give you three simple example how to get data from json file in node js. we will use require() and fs npm for read json file. let's see bellow example:

users.json

[

{

"id":1,

"name": "Hardik"

},

{

"id":2,

"name": "Paresh"

},

{

"id":3,

"name": "Rakesh"

},

{

"id":4,

"name": "Mahesh"

}

]

Example 1:

server.js

const users = require("./users");

console.log(users);

Output:

[

{ id: 1, name: 'Hardik' },

{ id: 2, name: 'Paresh' },

{ id: 3, name: 'Rakesh' },

{ id: 4, name: 'Mahesh' }

]

Example 2:

server.js

const fs = require('fs');

let rawdata = fs.readFileSync('users.json');

let users = JSON.parse(rawdata);

console.log(users);

Output:

[

{ id: 1, name: 'Hardik' },

{ id: 2, name: 'Paresh' },

{ id: 3, name: 'Rakesh' },

{ id: 4, name: 'Mahesh' }

]

Example 3:

server.js

const fs = require('fs');

fs.readFile('users.json', (err, data) => {

if (err) throw err;

let users = JSON.parse(data);

console.log(users);

});

Output:

[

{ id: 1, name: 'Hardik' },

{ id: 2, name: 'Paresh' },

{ id: 3, name: 'Rakesh' },

{ id: 4, name: 'Mahesh' }

]

i hope it can help you...

Tags :
Shares