Node.js6 min read

Working with JSON in Node.js

Learn to read, write, and manipulate JSON data in Node.js. Parse JSON files and handle API responses.

Sarah Chen
December 19, 2025
0.0k0

Working with JSON in Node.js

JSON is the standard data format. Node.js makes it easy.

Parse JSON String

```javascript const jsonString = '{"name": "Alice", "age": 25}'; const obj = JSON.parse(jsonString);

console.log(obj.name); // Alice console.log(obj.age); // 25 ```

Convert to JSON String

```javascript const obj = { name: 'Alice', age: 25 }; const jsonString = JSON.stringify(obj);

console.log(jsonString); // {"name":"Alice","age":25}

// Pretty print const pretty = JSON.stringify(obj, null, 2); console.log(pretty); // { // "name": "Alice", // "age": 25 // } ```

Read JSON File

```javascript const fs = require('fs').promises;

async function readJSON(filepath) { const data = await fs.readFile(filepath, 'utf8'); return JSON.parse(data); }

const config = await readJSON('config.json'); console.log(config); ```

**Simpler with require (for static files):** ```javascript const config = require('./config.json'); // Works but caches the file ```

Write JSON File

```javascript const fs = require('fs').promises;

async function writeJSON(filepath, data) { const json = JSON.stringify(data, null, 2); await fs.writeFile(filepath, json); }

const users = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' } ];

await writeJSON('users.json', users); ```

Update JSON File

```javascript async function updateJSON(filepath, updateFn) { const data = await readJSON(filepath); const updated = updateFn(data); await writeJSON(filepath, updated); }

// Add a user await updateJSON('users.json', users => { users.push({ id: 3, name: 'Charlie' }); return users; }); ```

Handle Errors

```javascript function safeJsonParse(str) { try { return JSON.parse(str); } catch (err) { console.error('Invalid JSON:', err.message); return null; } }

const data = safeJsonParse('invalid json'); // null const valid = safeJsonParse('{"ok": true}'); // {ok: true} ```

Working with API Responses

```javascript const https = require('https');

function fetchJSON(url) { return new Promise((resolve, reject) => { https.get(url, (res) => { let data = ''; res.on('data', chunk => data += chunk); res.on('end', () => resolve(JSON.parse(data))); }).on('error', reject); }); }

const user = await fetchJSON('https://api.github.com/users/octocat'); console.log(user.name); ```

JSON with Dates

```javascript const obj = { name: 'Event', date: new Date() };

const json = JSON.stringify(obj); // {"name":"Event","date":"2024-01-15T10:30:00.000Z"}

// Parse with date conversion const parsed = JSON.parse(json, (key, value) => { if (key === 'date') return new Date(value); return value; }); ```

Practical: Simple JSON Database

```javascript class JsonDB { constructor(filepath) { this.filepath = filepath; } async read() { try { const data = await fs.readFile(this.filepath, 'utf8'); return JSON.parse(data); } catch { return []; } } async write(data) { await fs.writeFile(this.filepath, JSON.stringify(data, null, 2)); } async add(item) { const data = await this.read(); data.push(item); await this.write(data); } }

const db = new JsonDB('data.json'); await db.add({ id: 1, name: 'Item 1' }); ```

Key Takeaway

Use `JSON.parse()` to read JSON strings, `JSON.stringify()` to create them. For files, combine with `fs` module. Always handle parse errors and use pretty printing for readable files.

#Node.js#JSON#Data#Beginner