Open In App

How to Parse JSON using Node.js?

JSON stands for JavaScript Object Notation. The text-based data exchange format data exchange format allows you to transfer data between different languages and platforms. JavaScript is commonly used to interact with JSON files. JSON parsing is a common task when working with data from APIs, configuration files, or databases. In this article, we will learn about How to parse JSON using Node.js.

The below mentioned are the approaches to parse JSON data in Node.js:

Using JSON.parse() method

This is the simplest way to parse JSON by using the built-in JSON.parse() method. This method takes a JSON string as input and returns a JavaScript object.

Example: This example shows the use of JSON.parse() method to parse JSON.

const jsonString = '{"name": "John", "age": 30}';
const jsonObject = JSON.parse(jsonString);

console.log(jsonObject.name); 
console.log(jsonObject.age);

Output
John
30

Using fs module

If your JSON data is stored in a file. you can read the file using Node.js's built-in fs module and then parse the JSON string.

Example: This example shows the use fs module to parse JSON.

const fs = require('fs');

fs.readFile('data.json', 'utf8', 
  (err, data) => {
     if (err) {
       console.error(err);
       return;
  }
  const jsonObject = JSON.parse(data);
  console.log(jsonObject);
});
// data.json
{"name": "John", "age": 30}

Output:

{"name": "John", "age": 30}

Using require() method

You can also directly require a JSON file. When you use require() with a .json file Node.js automatically parses the JSON data and returns it as a JavaScript object.

Example: This example shows the use of require() method to parse JSON.

const jsonObject = require('./data.json');
console.log(jsonObject);
// data.json
{"name": "John", "age": 30}

Output

{"name": "John", "age": 30}
Article Tags :