In this tutorial, we will learn how to fetch/read/get data from json file in Node js apps. JSON is a popular data format that is used to store and exchange data
In this tutorial , we will learn how to read and parse JSON files in Node.js with this step-by-step tutorial. JSON is a popular data format that is used to store and exchange data in a variety of applications. With Node.js, you can easily read and parse JSON files to access the data they contain.
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",
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.
Here is an example code snippet that loads the JSON file:
const fs = require('fs');
const data = fs.readFileSync('data.json', 'utf8');
In this code, you first import the
fs module and then call the
readFileSync method to read the contents of the
data.json file. The second argument to
readFileSync is the encoding of the file, which set to
utf8 to ensure that the data is returned as a string.
The data returned by
Here is an example code snippet that parses the JSON data:
const jsonData = JSON.parse(data);
In this code, you call the
JSON.parse method and pass in the
name property of the JSON data:
This code logs the value of the
name property of the JSON data to the console.
In this tutorial you learned how to fetch/read/get data from json file in Node js application.