Working with JSON Files
JSON (JavaScript Object Notation) is the most common format for storing and exchanging data in Node.js applications. Configuration files, database exports, API responses – they all use JSON. Let's learn how to work with JSON files effectively.
What is JSON?
JSON is a lightweight data format that's easy for humans to read and write, and easy for machines to parse and generate. It looks exactly like JavaScript objects.
{ "name": "John Doe", "age": 30, "email": "john@example.com", "hobbies": ["reading", "coding", "gaming"], "address": { "city": "New York", "zip": 10001 }}Think of JSON as a universal language that JavaScript (and many other languages) understand perfectly. It's like having a conversation between your code and files.
Reading JSON Files
Method 1: Using fs.readFile + JSON.parse
const fs = require('fs');
fs.readFile('config.json', 'utf8', (err, data) => { if (err) { console.error('Error reading file:', err); return; } try { const config = JSON.parse(data); console.log('Server port:', config.port); console.log('Database:', config.database); } catch (parseErr) { console.error('Invalid JSON format:', parseErr); }});Method 2: Using require() (Simplest for JSON)
Node.js can directly require JSON files – it automatically parses them!
<!-- This works for JSON files! -->const config = require('./config.json');
console.log('Server port:', config.port);
<!-- Note: require() caches the file, so changes won't be seen until restart -->Method 3: Using fs.promises with async/await
const fs = require('fs').promises;
async function loadConfig() { try { const data = await fs.readFile('config.json', 'utf8'); const config = JSON.parse(data); console.log('Config loaded', config); } catch (err) { console.error('Failed to load config:', err); }}
loadConfig();Writing JSON Files
When writing JSON, you need to convert JavaScript objects to JSON strings using `JSON.stringify()`.
const fs = require('fs').promises;
const user = { name: 'Alice', age: 25, email: 'alice@example.com', skills: ['JavaScript', 'Node.js', 'React']};
async function saveUser() { try { <!-- Convert to JSON string (pretty printed with 2 spaces) --> const jsonData = JSON.stringify(user, null, 2); await fs.writeFile('user.json', jsonData); console.log('User data saved!'); } catch (err) { console.error('Error saving user:', err); }}
saveUser();JSON.stringify() Options
| Parameter | Description |
|---|---|
| `value` | The object to convert to JSON |
| `replacer` | Function or array to filter properties (optional) |
| `space` | Number of spaces for indentation (pretty print) |
Using replacer to filter properties:
<!-- Only include specific properties -->const json = JSON.stringify(user, ['name', 'email']);<!-- {"name":"Alice","email":"alice@example.com"} -->
<!-- Using a function to transform values -->const json2 = JSON.stringify(user, (key, value) => { if (key === 'password') return undefined; <!-- Exclude password --> return value;});Updating JSON Files (Read-Modify-Write Pattern)
Often you need to update existing JSON files – read, modify, write back.
const fs = require('fs').promises;
async function updateCounter() { try { <!-- 1. Read existing data --> const data = await fs.readFile('counter.json', 'utf8'); const counter = JSON.parse(data); <!-- 2. Modify the data --> counter.visits = (counter.visits || 0) + 1; counter.lastVisit = new Date().toISOString(); <!-- 3. Write back --> await fs.writeFile('counter.json', JSON.stringify(counter, null, 2)); console.log('Visits updated:', counter.visits); } catch (err) { console.error('Error:', err); }}
updateCounter();Practical Example: Simple Database with JSON
Create a simple key-value store using a JSON file.
const fs = require('fs').promises;
class JsonDB { constructor(filePath) { this.filePath = filePath; } async init() { try { await fs.access(this.filePath); } catch { <!-- File doesn't exist, create with empty object --> await fs.writeFile(this.filePath, '{}'); } } async get(key) { const data = await fs.readFile(this.filePath, 'utf8'); const obj = JSON.parse(data); return obj[key]; } async set(key, value) { const data = await fs.readFile(this.filePath, 'utf8'); const obj = JSON.parse(data); obj[key] = value; await fs.writeFile(this.filePath, JSON.stringify(obj, null, 2)); return true; } async delete(key) { const data = await fs.readFile(this.filePath, 'utf8'); const obj = JSON.parse(data); delete obj[key]; await fs.writeFile(this.filePath, JSON.stringify(obj, null, 2)); return true; }}
async function example() { const db = new JsonDB('mydb.json'); await db.init(); await db.set('user1', { name: 'John', age: 30 }); await db.set('user2', { name: 'Jane', age: 25 }); const user1 = await db.get('user1'); console.log('User1:', user1);}
example();Two Minute Drill
- JSON is the standard data format for Node.js applications.
- Use `JSON.parse()` to convert JSON string to JavaScript object.
- Use `JSON.stringify()` to convert object to JSON string.
- You can `require()` JSON files directly – Node.js parses them automatically.
- For updates, use read-modify-write pattern.
- Always handle JSON parsing errors – malformed JSON will throw an exception.
Need more clarification?
Drop us an email at career@quipoinfotech.com
