jsondecode.com logo

HomeChevronBlogChevronJSON in Node.js: Complete Developer Guide

Blog post

JSON in Node.js: Complete Developer Guide

Working with JSON in Node.js — reading files, HTTP APIs, streaming large files, and common pitfalls. With code examples.

author

Shashank Jain

Author

14/06/20261 minute 55 seconds read
JSON in Node.js: Complete Developer GuideJSON in Node.js: Complete Developer Guide

Article

Parsing JSON in Node.js

Node.js has built-in JSON support — no imports required:

const json = '{"name": "Alice", "age": 30}';
const obj = JSON.parse(json);
console.log(obj.name); // 'Alice'

const backToJson = JSON.stringify(obj, null, 2);
console.log(backToJson);

Reading JSON Files

// Synchronous (fine for startup/config)
const fs = require('fs');
const config = JSON.parse(fs.readFileSync('./config.json', 'utf8'));

// Async with fs.promises
const { readFile } = require('fs/promises');
const data = JSON.parse(await readFile('./data.json', 'utf8'));

// require() also parses JSON automatically
const pkg = require('./package.json');
console.log(pkg.version);

Writing JSON Files

const fs = require('fs/promises');

const data = { users: [{ id: 1, name: 'Alice' }] };
await fs.writeFile('./output.json', JSON.stringify(data, null, 2));

JSON in HTTP APIs (fetch)

// GET request
const res = await fetch('https://api.example.com/users');
const users = await res.json();

// POST with JSON body
const response = await fetch('https://api.example.com/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Bob', email: 'bob@example.com' })
});
const created = await response.json();

Streaming Large JSON Files

For files too large to load into memory, use stream-json:

const { parser } = require('stream-json');
const { streamArray } = require('stream-json/streamers/StreamArray');
const fs = require('fs');

const pipeline = fs.createReadStream('large.json')
  .pipe(parser())
  .pipe(streamArray());

pipeline.on('data', ({ value }) => {
  // Process one item at a time
  console.log(value.id);
});

pipeline.on('end', () => console.log('Done'));

Common Pitfalls

PitfallExampleFix
Parsing undefinedJSON.parse(undefined) throwsCheck value exists first
Circular referencesJSON.stringify throws on circular objectsUse flatted or custom replacer
BigInt valuesJSON.stringify(9007199254740993n) throwsConvert to string before stringifying
Date objectsDates serialize to ISO strings, not restored on parseUse a reviver function or store as timestamps

JSON with Express.js

const express = require('express');
const app = express();

app.use(express.json()); // Parse JSON request bodies

app.post('/api/users', (req, res) => {
  const { name, email } = req.body; // Already parsed
  res.json({ id: 1, name, email }); // Auto-serialized
});

FAQ

What's the difference between require() and fs.readFile() for JSON?

require('./data.json') is synchronous, cached after first load, and parsed automatically. fs.readFile is async, not cached, and needs manual JSON.parse. Use require() for static config, fs for dynamic/large data files.

How do I handle JSON parse errors gracefully?

Wrap in try/catch: try { JSON.parse(str) } catch (e) { /* handle */ }. Never trust user-supplied JSON strings.

Can Node.js import JSON with ES modules?

Yes, with an import assertion: import data from './data.json' assert { type: 'json' };. This is stable in Node.js 18+.

How do I pretty-print JSON to the console?

Use console.log(JSON.stringify(obj, null, 2)) or console.dir(obj, { depth: null }) for deep objects.

What's the maximum JSON file size Node.js can parse?

Theoretically limited by V8's max string size (~1GB). Practically, files over 50–100MB should use streaming to avoid blocking the event loop and exhausting memory.

Keep reading

Recent blogs

View all

If jsondecode.com saved you time, share it with your team

Free forever. No ads. No sign-up. Help other developers find it.