ItSolutionStuff.com

How to Get Data from Json File in Node JS?

By Hardik Savani • May 28, 2021
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: Node JS
Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Push Element in Array in Node JS?

Read Now →

How to use Underscore JS in Node JS App?

Read Now →

Node JS Sort Array of Objects by Value Example

Read Now →

Node JS Foreach Loop Array Example

Read Now →

How to Create and Use .env File in Node JS?

Read Now →

Axios HTTP requests in Node JS Example

Read Now →

Node JS Http Request with Headers Example

Read Now →

Node JS Make HTTP Put Request Example

Read Now →

Node JS Make HTTP Delete Request Example

Read Now →

Node JS Make Http Get Request with Parameters Example

Read Now →

How to make an HTTP POST request in Node JS?

Read Now →