You can parse JSON data using the built-in JSON.parse() method, which converts a JSON string into a JavaScript object. Here's how you can do it:
Parsing a JSON String:
If you have a JSON string, use JSON.parse() to convert it into a JavaScript object:
const jsonString = '{"name": "John Doe", "age": 30}';
const jsonObject = JSON.parse(jsonString);
console.log(jsonObject.name); // Output: John Doe
Reading and Parsing a JSON File Asynchronously:
To read and parse a JSON file asynchronously, utilize the fs module:
const fs = require('fs');
fs.readFile('path/to/file.json', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
try {
const jsonObject = JSON.parse(data);
console.log(jsonObject);
} catch (parseErr) {
console.error('Error parsing JSON:', parseErr);
}
});
Reading and Parsing a JSON File Synchronously:
For synchronous file reading, you can use fs.readFileSync():
const fs = require('fs');
try {
const data = fs.readFileSync('path/to/file.json', 'utf8');
const jsonObject = JSON.parse(data);
console.log(jsonObject);
} catch (err) {
console.error('Error reading or parsing file:', err);
}
Using require() for Static JSON Files:
For loading static JSON files, you can use require(). Note that this method caches the file content and is synchronous:
const jsonObject = require('./path/to/file.json');
console.log(jsonObject);