Working with JSON data in Node.js is a common task, especially when dealing with APIs or reading/writing configuration files. Node.js provides built-in modules to handle JSON data. Here's an overview of how to work with JSON data in Node.js:
Parsing JSON:
1. Parsing JSON from a String:
To parse JSON data from a string, you can use JSON.parse():
const jsonString = '{"name": "John Doe", "age": 30}';
const parsedData = JSON.parse(jsonString);
console.log(parsedData.name); // Output: John Doe
2. Reading JSON from a File:
If you have a JSON file, you can read and parse it using the fs module: