How to use fs module In NodeJS
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}
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:
Table of Content
- Using JSON.parse() method
- Reading JSON from a File
- Using require() method
Contact Us