How to Get Data from Json File in Node JS?

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

Hello Brother,

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 lesson.

In this post, i will give you three simple lesson 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 lesson:

users.json

[

{

"id":1,

"name": "Sagor"

},

{

"id":2,

"name": "Paresh"

},

{

"id":3,

"name": "Rakesh"

},

{

"id":4,

"name": "Mahesh"

}

]

Lesson 1:

server.js

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

console.log(users);

Result:-

[

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

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

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

{ id: 4, name: 'Mahesh' }

]

Lesson 2:

server.js

const fs = require('fs');

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

let users = JSON.parse(rawdata);

console.log(users);

Result:-

[

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

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

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

{ id: 4, name: 'Mahesh' }

]

Lesson 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);

});

Result:-

[

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

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

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

{ id: 4, name: 'Mahesh' }

]

thank you very much for following up with me.

Tags

Recent Posts

Related Posts