Get Data from Json File in Node JS Example

24-Mar-2023

.

Admin

Get Data from Json File in Node JS Example

Hi Dev,

I am going to explain to you an example of getting data from json file in node js. Here you will learn How to Fetch Data from Json File in Node JS. if you want to see example of How to Get Data from Json File in Node JS then you are in the right place. let’s discuss in node js to get data from a file. Alright, let’s dive into the steps.

Here you will learn How to Fetch Data from Json File in Node JS. this example will help you How to Get Data from Json File in Node JS. This article goes into detail on node js getting data from a file. So, let's follow a few steps to create an example of how can get data in node js from the file.

Step 1 : Create a JSON file


The first step is to create a JSON file containing the data you want to fetch. You can create the file using any text editor, and save it with a .json extension. Here is an example of a simple JSON file:

{

"name": "John Doe",

"age": 30,

"email": "johndoe@example.com"

}

Step 2 : Load the JSON file

To load the JSON file into your Node.js application, you can use the built-in fs module, which provides an API for interacting with the file system. The fs module includes a method called readFileSync, which reads the contents of a file synchronously and returns it as a string.

const fs = require('fs');

const data = fs.readFileSync('data.json', 'utf8');

Step 3 : Parse the JSON data

The data returned by readFileSync is a string, but you need to parse it into a JavaScript object so that can work with it in our code. To parse the JSON data, you can use the built-in JSON.parse method, which takes a JSON string as input and returns a JavaScript object.

const jsonData = JSON.parse(data);

In this code, you call the JSON. parse method and pass in the data string that is loaded from the file. The result is a JavaScript object that you can now work with within our code.

Step 4 : Access the JSON data

Now that you have loaded and parsed the JSON data, and can access it just like any other JavaScript object. Here is an example code snippet that accesses the name property of the JSON data:

   

console.log(jsonData.name);

This code logs the value of the name property of the JSON data to the console.

#Node.js Express