JSON

suggest change

JSON (JavaScript Object Notation) is the most common data format in Node.js programs: package.json, configuration files, REST APIs, message queues and log files all use it.

JSON support is built into JavaScript, so you don't need any packages. There are two functions:

Basics

const user = {
  name: 'Alice',
  age: 31,
  admin: true,
  tags: ['dev', 'ops'],
  address: { city: 'Berlin', zip: null },
};

const json = JSON.stringify(user);
console.log(json);
// {"name":"Alice","age":31,"admin":true,"tags":["dev","ops"],"address":{"city":"Berlin","zip":null}}

const copy = JSON.parse(json);
console.log(copy.address.city); // Berlin
console.log(copy === user);     // false, it's a new object

JSON is stricter than JavaScript object literals:

Top-level values don't have to be objects. Any JSON value is valid:

console.log(JSON.parse('42'));         // 42
console.log(JSON.parse('"hello"'));    // hello
console.log(JSON.parse('[1, 2, 3]'));  // [ 1, 2, 3 ]
console.log(JSON.parse('null'));       // null
console.log(JSON.stringify('hi'));     // "hi"  (with quotes)

Pretty printing

The third argument of JSON.stringify controls indentation. Pass a number of spaces or a string such as '\t':

const config = { port: 8080, db: { host: 'localhost', pool: 10 } };

console.log(JSON.stringify(config, null, 2));

Output:

{
  "port": 8080,
  "db": {
    "host": "localhost",
    "pool": 10
  }
}

Use compact output (no indentation) for network traffic and machine-to-machine communication; use indentation for files people will read and edit.

How values are converted

JSON.stringify silently changes or drops values that JSON can't represent. This is a common source of bugs:

const data = {
  str: 'text',
  undef: undefined,          // dropped
  fn() { return 1; },        // dropped
  sym: Symbol('x'),          // dropped
  nan: NaN,                  // becomes null
  inf: Infinity,             // becomes null
  date: new Date(Date.UTC(2026, 0, 15, 10, 30)), // ISO string
  regex: /abc/g,             // becomes {}
  map: new Map([['a', 1]]),  // becomes {}
  set: new Set([1, 2]),      // becomes {}
  arr: [undefined, () => 1, NaN], // nulls inside arrays
};

console.log(JSON.stringify(data, null, 2));

Output:

{
  "str": "text",
  "nan": null,
  "inf": null,
  "date": "2026-01-15T10:30:00.000Z",
  "regex": {},
  "map": {},
  "set": {},
  "arr": [
    null,
    null,
    null
  ]
}

A few other rules:

The last point matters when you round-trip data. After JSON.parse you get plain objects, arrays, strings, numbers, booleans and null, nothing else. A Date comes back as a string, and class instances don't have their methods.

Customizing output with toJSON

If an object has a toJSON() method, JSON.stringify serializes its return value instead of the object. This is how Date produces ISO strings.

You can use it to control how your classes are serialized, for example to hide secrets:

class User {
  constructor(name, email, passwordHash) {
    this.name = name;
    this.email = email;
    this.passwordHash = passwordHash;
  }

  toJSON() {
    const { passwordHash, ...rest } = this;
    return rest;
  }
}

const u = new User('bob', 'bob@example.com', '$2b$10$abc...');
console.log(JSON.stringify(u)); // {"name":"bob","email":"bob@example.com"}

Maps and Sets serialize to {}, so convert them explicitly:

const scores = new Map([['alice', 10], ['bob', 7]]);
const ids = new Set([3, 1, 2]);

const json = JSON.stringify({
  scores: Object.fromEntries(scores),
  ids: [...ids],
});
console.log(json); // {"scores":{"alice":10,"bob":7},"ids":[3,1,2]}

const parsed = JSON.parse(json);
const scores2 = new Map(Object.entries(parsed.scores));
const ids2 = new Set(parsed.ids);
console.log(scores2.get('alice'), ids2.has(2)); // 10 true

The replacer argument

The second argument of JSON.stringify is a replacer. If it's an array, only the listed keys are included (at every nesting level):

const user = { id: 1, name: 'Alice', password: 'secret', role: 'admin' };

console.log(JSON.stringify(user, ['id', 'name']));
// {"id":1,"name":"Alice"}

If it's a function, it's called for every key/value pair. Whatever it returns is serialized; returning undefined removes the property:

const order = {
  id: 1001n, // BigInt would normally throw
  customer: 'alice',
  apiKey: 'sk-12345',
  total: 99.5,
};

const json = JSON.stringify(order, (key, value) => {
  if (typeof value === 'bigint') return value.toString();
  if (key === 'apiKey') return undefined;
  return value;
});

console.log(json); // {"id":"1001","customer":"alice","total":99.5}

The function is first called with an empty key '' and the whole object as the value, then recursively for each property. Inside the function, this is the object containing the current key.

Note that toJSON() runs before the replacer, so for a Date the replacer already sees a string. If you need the original value use this[key] (with a regular function, not an arrow function).

The reviver argument

JSON.parse takes an optional reviver function, the mirror of the replacer. It's called for each key/value pair from the innermost values outward, and its return value replaces the parsed value.

A typical use is turning ISO date strings back into Date objects:

const isoDate = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/;

function reviver(key, value) {
  if (typeof value === 'string' && isoDate.test(value)) {
    return new Date(value);
  }
  return value;
}

const json = '{"event":"deploy","at":"2026-01-15T10:30:00.000Z"}';
const obj = JSON.parse(json, reviver);

console.log(obj.at instanceof Date); // true
console.log(obj.at.getUTCHours());   // 10

Handling parse errors

JSON.parse throws a SyntaxError on invalid input. Data coming from files, users or the network can always be malformed, so wrap parsing in try / catch:

function safeParse(text, fallback = null) {
  try {
    return JSON.parse(text);
  } catch (err) {
    console.error('invalid JSON:', err.message);
    return fallback;
  }
}

console.log(safeParse('{"a": 1}'));   // { a: 1 }
console.log(safeParse("{'a': 1}"));   // null, single quotes are not allowed
console.log(safeParse('{"a": 1,}'));  // null, trailing comma
console.log(safeParse(''));           // null, empty string is not valid JSON

In recent Node.js versions the error message includes the position, e.g. Expected property name or '}' in JSON at position 1 (line 1 column 2), which helps find the problem in large files.

Parsing only checks syntax. JSON.parse doesn't guarantee that the data has the shape you expect, so validate fields before using them:

function parseUser(text) {
  const data = JSON.parse(text);
  if (typeof data !== 'object' || data === null || Array.isArray(data)) {
    throw new TypeError('expected a JSON object');
  }
  if (typeof data.name !== 'string' || !Number.isInteger(data.age)) {
    throw new TypeError('invalid user');
  }
  return { name: data.name, age: data.age };
}

For bigger schemas use a validation library such as zod or ajv.

Reading and writing JSON files

There's no special API for JSON files: read the file as text, then parse it.

import { readFile, writeFile } from 'node:fs/promises';

async function readJson(path) {
  const text = await readFile(path, 'utf8');
  return JSON.parse(text);
}

async function writeJson(path, data) {
  await writeFile(path, JSON.stringify(data, null, 2) + '\n', 'utf8');
}

await writeJson('settings.json', { theme: 'dark', fontSize: 14 });
const settings = await readJson('settings.json');
settings.fontSize = 16;
await writeJson('settings.json', settings);

console.log(await readFile('settings.json', 'utf8'));

Output:

{
  "theme": "dark",
  "fontSize": 16
}

Synchronous versions are fine for small config files read at startup:

import { readFileSync } from 'node:fs';

const config = JSON.parse(readFileSync('./config.json', 'utf8'));

If a crash in the middle of writing would corrupt an important file, write to a temporary file first and then rename() it over the original. On the same filesystem a rename replaces the file in one step.

import { writeFile, rename } from 'node:fs/promises';

async function writeJsonAtomic(path, data) {
  const tmp = `${path}.${process.pid}.tmp`;
  await writeFile(tmp, JSON.stringify(data, null, 2));
  await rename(tmp, path);
}

See Writing to a file using writeFile or writeFileSync for more on writing files.

Importing JSON modules

In CommonJS, require() parses .json files directly:

const pkg = require('./package.json');
console.log(pkg.name, pkg.version);

In ES modules, use an import attribute:

import pkg from './package.json' with { type: 'json' };

console.log(pkg.version);

The with { type: 'json' } part is required. Import attributes are supported since Node.js 18.20 and 20.10; the older assert { type: 'json' } syntax was removed in Node.js 22.

Both require() and import cache the result: the file is read once, and every importer gets the same object. That's fine for static data, but if the file changes at runtime or you need a fresh copy, use readFile and JSON.parse instead.

JSON over HTTP

With the built-in fetch, send JSON by stringifying the body and setting the Content-Type header. Read JSON responses with res.json():

const res = await fetch('https://httpbin.org/post', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Alice', age: 31 }),
});

if (!res.ok) {
  throw new Error(`HTTP ${res.status}`);
}

const data = await res.json(); // reads body and calls JSON.parse
console.log(data.json); // httpbin echoes the parsed body: { age: 31, name: 'Alice' }

res.json() rejects with a SyntaxError if the body isn't valid JSON, which often happens when a server returns an HTML error page.

On the server side with the plain http module you have to collect the request body yourself. Always limit the size, or a client can make your server buffer gigabytes:

import http from 'node:http';

const MAX_BODY = 1024 * 1024; // 1 MB

async function readJsonBody(req) {
  let size = 0;
  const chunks = [];
  for await (const chunk of req) {
    size += chunk.length;
    if (size > MAX_BODY) throw new Error('body too large');
    chunks.push(chunk);
  }
  return JSON.parse(Buffer.concat(chunks).toString('utf8'));
}

const server = http.createServer(async (req, res) => {
  let body;
  try {
    body = await readJsonBody(req);
  } catch (err) {
    res.writeHead(400, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ error: err.message }));
    return;
  }

  res.writeHead(200, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ received: body }));
});

server.listen(3000);

Test it with curl:

$ curl -s -X POST localhost:3000 -H 'Content-Type: application/json' -d '{"x":1}'
{"received":{"x":1}}

In Express, the express.json() middleware does this for you (with a default limit of 100 kB) and puts the result in req.body; res.json(obj) sends a JSON response. See JSON API with ExpressJS.

Newline-delimited JSON (NDJSON)

JSON.parse needs the whole document in memory. For logs and large data exports a common format is NDJSON (also called JSON Lines): one JSON value per line. It can be appended to and processed line by line:

import { appendFile } from 'node:fs/promises';
import { createReadStream } from 'node:fs';
import readline from 'node:readline';

// writing: one JSON.stringify per line, no indentation
for (const level of ['info', 'warn', 'error']) {
  const entry = { time: new Date().toISOString(), level, msg: `a ${level} message` };
  await appendFile('app.log', JSON.stringify(entry) + '\n');
}

// reading: parse each line separately
const rl = readline.createInterface({
  input: createReadStream('app.log'),
  crlfDelay: Infinity,
});

for await (const line of rl) {
  if (!line.trim()) continue;
  const entry = JSON.parse(line);
  if (entry.level === 'error') console.log(entry.msg);
}
// a error message

Memory use stays constant no matter how big the file is. See Reading a file line by line for details.

Circular references

Objects that reference themselves can't be serialized:

const node = { name: 'root' };
node.self = node;

try {
  JSON.stringify(node);
} catch (err) {
  console.log(err.name); // TypeError
}

If you need to serialize such data (e.g. for logging), use a replacer that tracks objects on the current path and replaces repeats:

function decycle() {
  const ancestors = [];
  return function (key, value) {
    if (typeof value !== 'object' || value === null) return value;
    // `this` is the object containing `key`; drop ancestors we've left
    while (ancestors.length > 0 && ancestors.at(-1) !== this) {
      ancestors.pop();
    }
    if (ancestors.includes(value)) return '[Circular]';
    ancestors.push(value);
    return value;
  };
}

const a = { name: 'a' };
a.self = a;
a.list = [a, { name: 'b' }];

console.log(JSON.stringify(a, decycle()));
// {"name":"a","self":"[Circular]","list":["[Circular]",{"name":"b"}]}

For just looking at such objects, util.inspect() (used by console.log) handles cycles and prints <ref *1> markers.

Large numbers

JSON numbers are parsed into JavaScript numbers (64-bit floats), which represent integers exactly only up to Number.MAX_SAFE_INTEGER (9007199254740991). Larger IDs, like the ones from some databases and APIs, silently lose precision:

const parsed = JSON.parse('{"id": 12345678901234567890}');
console.log(parsed.id); // 12345678901234567000

The usual fix is to send big integers as strings. If you can't change the producer, Node.js 21+ passes the original source text to the reviver as a third argument:

const json = '{"id": 12345678901234567890, "count": 5}';

const obj = JSON.parse(json, (key, value, context) => {
  if (typeof value === 'number' && !Number.isSafeInteger(value) && context?.source) {
    return BigInt(context.source);
  }
  return value;
});

console.log(obj.id);    // 12345678901234567890n
console.log(obj.count); // 5

To write a BigInt back as an unquoted JSON number, use JSON.rawJSON() in a replacer:

const out = JSON.stringify({ id: 12345678901234567890n }, (key, value) =>
  typeof value === 'bigint' ? JSON.rawJSON(value.toString()) : value
);
console.log(out); // {"id":12345678901234567890}

JSON for deep copies

JSON.parse(JSON.stringify(obj)) is an old trick for deep-copying objects, but it loses dates, undefined, Maps, Sets and anything else JSON can't represent. Use the built-in structuredClone() instead:

const original = { when: new Date(), tags: new Set(['a']), nested: { n: 1 } };

const viaJson = JSON.parse(JSON.stringify(original));
console.log(typeof viaJson.when, viaJson.tags); // string {}

const clone = structuredClone(original);
console.log(clone.when instanceof Date, clone.tags); // true Set(1) { 'a' }
clone.nested.n = 2;
console.log(original.nested.n); // 1

Summary

Task Code
object to JSON JSON.stringify(obj)
pretty-printed JSON JSON.stringify(obj, null, 2)
JSON to object JSON.parse(text)
keep only some keys JSON.stringify(obj, ['id', 'name'])
transform while serializing JSON.stringify(obj, (k, v) => ...)
transform while parsing JSON.parse(text, (k, v) => ...)
custom serialization define toJSON() on the class
read a JSON file JSON.parse(await readFile(path, 'utf8'))
import JSON in ESM import data from './x.json' with { type: 'json' }
parse fetch response await res.json()
deep copy structuredClone(obj)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents