How to Get Data from Json File in 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...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- How to Push Element in Array in Node JS?
- How to use Underscore JS in Node JS App?
- Node JS Sort Array of Objects by Value Example
- Node JS Foreach Loop Array Example
- How to Create and Use .env File in Node JS?
- Axios HTTP requests in Node JS Example
- Node JS Http Request with Headers Example
- Node JS Make HTTP Put Request Example
- Node JS Make HTTP Delete Request Example
- Node JS Make Http Get Request with Parameters Example
- How to make an HTTP POST request in Node JS?