Node.js and JSON: The Basics
JSON (JavaScript Object Notation) is a lightweight data format that’s easy for humans to read and write, and easy for machines to parse and generate. Node.js has excellent built-in support for JSON, making it a breeze to work with.
Parsing JSON
To parse a JSON string into a JavaScript object:
const jsonString = '{"name": "John", "age": 30}';
const obj = JSON.parse(jsonString);
console.log(obj.name); // Outputs: John
Stringifying JavaScript Objects
To convert a JavaScript object into a JSON string:
const obj = { name: "Jane", age: 25 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // Outputs: {"name":"Jane","age":25}
Reading JSON Files
Node.js makes it easy to read JSON files:
const fs = require('fs');
fs.readFile('data.json', 'utf8', (err, data) => {
if (err) {
console.error('Error reading file:', err);
return;
}
const obj = JSON.parse(data);
console.log(obj);
});
Writing JSON Files
Similarly, you can write JSON data to a file:
const fs = require('fs');
const obj = { name: "Alice", age: 28 };
const jsonString = JSON.stringify(obj);
fs.writeFile('output.json', jsonString, (err) => {
if (err) {
console.error('Error writing file:', err);
} else {
console.log('Data written to file');
}
});
JSON is widely used in Node.js applications for configuration files, API responses, and data storage. Understanding these basics will help you handle JSON data effectively in your Node.js projects.