JSON in JavaScript With parse stringify and Every Option
JSON.stringify and JSON.parse take replacer, indent and reviver options and drop undefined, functions and symbols. See each option and the big number trap.

JSON looks like JavaScript object syntax, and that resemblance causes most of the mistakes people make with it. It is a text format with its own rules: no undefined, no functions, no comments, double quotes only and numbers with no distinction between integers and floats. Two functions convert between text and values, and each takes options that most developers never use and then reinvent by hand. This post goes through JSON.stringify() and JSON.parse() with real output from Node.js 24, covers what each option does, shows what gets silently lost and how to avoid it, and ends on the large number problem and the standard fix. The values JSON cannot hold are the same ones covered in the post on structuredClone().
What stringify does with each type
The output depends on the type of each value, and several types are dropped or changed with no error.
const sample = {
string: "text",
number: 1.5,
boolean: false,
nothing: null,
missing: undefined,
fn() {},
symbol: Symbol("s"),
nan: NaN,
infinite: Infinity,
date: new Date(Date.UTC(2026, 0, 2, 3, 4, 5)),
nested: { list: [1, undefined, () => {}, Symbol("x"), NaN] },
set: new Set([1]),
map: new Map([["k", 1]]),
};
console.log(JSON.stringify(sample));
console.log(JSON.stringify(undefined), JSON.stringify(() => {}), JSON.stringify("x"), JSON.stringify(null));{"string":"text","number":1.5,"boolean":false,"nothing":null,"nan":null,"infinite":null,"date":"2026-01-02T03:04:05.000Z","nested":{"list":[1,null,null,null,null]},"set":{},"map":{}}
undefined undefined "x" nullProperties holding undefined, a function or a symbol vanished from the object. In arrays the same values became null, since arrays cannot have gaps. NaN and Infinity became null. The date was serialized to an ISO string by its own toJSON() method, and the set and map became empty objects. Stringifying a bare undefined or function returns undefined and not the text "null", which means JSON.stringify can return a non-string.
The replacer
The second argument is either an array of property names to keep, or a function called for every key and value.
const user = {
id: 7,
name: "Ada",
password: "change-me",
address: { city: "London", zip: "N1" },
tags: ["a", "b"],
};
console.log(JSON.stringify(user, ["id", "name"]));
console.log(JSON.stringify(user, ["name", "address", "city"]));
const redacted = JSON.stringify(user, (key, value) => {
if (key === "password") return undefined;
if (typeof value === "number") return value * 10;
return value;
});
console.log(redacted);
const seen = [];
JSON.stringify({ a: { b: 1 } }, function (key, value) {
seen.push(`${JSON.stringify(key)} in ${this === undefined ? "?" : typeof this}`);
return value;
});
console.log(seen);{"id":7,"name":"Ada"}
{"name":"Ada","address":{"city":"London"}}
{"id":70,"name":"Ada","address":{"city":"London","zip":"N1"},"tags":["a","b"]}
[ '"" in object', '"a" in object', '"b" in object' ]An array replacer is a whitelist applied at every level, so "city" had to be listed explicitly to survive inside address. A function replacer sees each key and value, and returning undefined removes the property, which is the way to redact a field. The first call receives an empty-string key and the whole value, then the function walks down. this inside a function replacer is the object that holds the key. A replacer array also fixes the key order of the output, which is occasionally useful for stable diffs.
Indentation
The third argument turns the output into readable text. A number sets the indent width up to 10, and a string up to 10 characters is used as the indent itself.
const config = { name: "app", ports: [80, 443], tls: { enabled: true } };
console.log(JSON.stringify(config, null, 2));
console.log(JSON.stringify(config, null, "--"));
console.log(JSON.stringify(config, null, 99).split("\n")[1].length);
console.log(JSON.stringify([], null, 2), JSON.stringify({}, null, 2));{
"name": "app",
"ports": [
80,
443
],
"tls": {
"enabled": true
}
}
{
--"name": "app",
--"ports": [
----80,
----443
--],
--"tls": {
----"enabled": true
--}
}
24
[] {}A width above 10 is clamped, so the second line of the large-indent output has ten spaces before the key. Empty arrays and objects stay on one line. Pretty printing costs size, so keep it for logs and files that people read and use the compact form on the wire.
toJSON controls serialization of a value
Any object with a toJSON() method is serialized as whatever the method returns. Date has one, and your classes can too.
class Money {
constructor(cents, currency) {
this.cents = cents;
this.currency = currency;
}
toJSON() {
return { amount: (this.cents / 100).toFixed(2), currency: this.currency };
}
}
const order = {
id: 1,
total: new Money(1999, "USD"),
created: new Date(Date.UTC(2026, 4, 6)),
};
console.log(JSON.stringify(order));
const withReplacer = JSON.stringify(order, (key, value) => (typeof value === "bigint" ? value.toString() : value));
console.log(withReplacer.length > 0);
try {
JSON.stringify({ id: 10n });
} catch (error) {
console.log(error.name + ": " + error.message);
}{"id":1,"total":{"amount":"19.99","currency":"USD"},"created":"2026-05-06T00:00:00.000Z"}
true
TypeError: Do not know how to serialize a BigIntThe money object chose its own wire format, and the date used its built-in ISO form. A bigint has no toJSON and throws, so the replacer shows the usual workaround of writing it as a string. The toJSON method receives the property key as an argument, which lets one class serialize differently depending on where it appears.
Parsing and its errors
JSON.parse() accepts only strict JSON. Single quotes, trailing commas, comments, unquoted keys and undefined are all errors.
const inputs = [
'{"a": 1}',
"{'a': 1}",
'{"a": 1,}',
'{a: 1}',
'// comment\n{"a": 1}',
"undefined",
"",
"NaN",
];
for (const text of inputs) {
try {
console.log(JSON.stringify(text).padEnd(22), "ok", JSON.stringify(JSON.parse(text)));
} catch (error) {
console.log(JSON.stringify(text).padEnd(22), error.name);
}
}"{\"a\": 1}" ok {"a":1}
"{'a': 1}" SyntaxError
"{\"a\": 1,}" SyntaxError
"{a: 1}" SyntaxError
"// comment\n{\"a\": 1}" SyntaxError
"undefined" SyntaxError
"" SyntaxError
"NaN" SyntaxErrorOnly the first input parsed. Every deviation from strict JSON throws a SyntaxError. Parsing is also where untrusted data enters your program, so parse inside a try, validate the result against the shape you expect and never assume the type of a field. Parsing a __proto__ key creates an ordinary property, and the danger arises when the result is later merged, as discussed in the post on objects.
The reviver
The reviver is a function called bottom-up for every key and value, and what it returns replaces the value. It is the natural place to convert dates and other typed values.
const text = '{"id":1,"created":"2026-05-06T00:00:00.000Z","items":[{"when":"2026-01-02T03:04:05.000Z","qty":2}]}';
const isoDate = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/;
const parsed = JSON.parse(text, (key, value) => {
if (typeof value === "string" && isoDate.test(value)) return new Date(value);
return value;
});
console.log(parsed.created instanceof Date, parsed.items[0].when.getUTCFullYear());
const dropped = JSON.parse('{"keep":1,"secret":2,"nested":{"secret":3,"ok":4}}', (key, value) =>
key === "secret" ? undefined : value,
);
console.log(dropped);true 2026
{ keep: 1, nested: { ok: 4 } }Strings matching the ISO pattern became Date objects at any depth, and returning undefined removed the property. Matching on a pattern converts any string that looks like a date, including ones that were only text, so prefer converting by field name or by schema when the shape is known. A round trip of a date through JSON gives a string, and the reviver is the explicit step that restores it.
Large integers
JSON numbers have no size limit in the text, and JSON.parse turns them into doubles, which lose digits beyond 2^53.
const text = '{"id": 12345678901234567890, "small": 42}';
console.log(JSON.parse(text).id);
console.log(JSON.parse(text).id === 12345678901234567890);
console.log(Number.MAX_SAFE_INTEGER);
const exact = JSON.parse(text, (key, value, context) =>
key === "id" ? BigInt(context.source) : value,
);
console.log(exact.id, typeof exact.id);
const output = JSON.stringify({ id: JSON.rawJSON("12345678901234567890") });
console.log(output);
console.log(JSON.isRawJSON(JSON.rawJSON("1")));12345678901234567000
true
9007199254740991
12345678901234567890n bigint
{"id":12345678901234567890}
trueThe default parse rounded the id to the nearest double and printed 12345678901234567000. The reviver's third argument, context.source, holds the original text of a primitive value, so BigInt(context.source) recovers every digit. JSON.rawJSON() goes the other way: it emits a number's digits exactly when stringifying, with no rounding. Both are part of ES2026 and work in Node.js 24, and current Chromium. Where they are not available, the safe protocol is to send large ids as strings, as covered in the post on BigInt.
Cycles and sharing
JSON is a tree, and a cycle has no representation. The error message names the path.
const parent = { name: "parent", children: [] };
const child = { name: "child", parent };
parent.children.push(child);
try {
JSON.stringify(parent);
} catch (error) {
console.log(error.name);
console.log(error.message.split("\n")[0]);
}
const shared = { x: 1 };
const copy = JSON.parse(JSON.stringify({ a: shared, b: shared }));
console.log(copy.a === copy.b);TypeError
Converting circular structure to JSON
falseThe cycle throws a TypeError naming the structure. Shared references are written twice and come back as two separate objects, so a round trip loses the fact that a and b were the same object. structuredClone() preserves both cycles and sharing, which makes it the better tool for copying, and JSON remains the format for text.
Round trip tests
Any code that writes JSON and reads it back deserves a test that compares the result with the original, because the lossy cases from the first example hide in plain sight. A round trip test is three lines, and it fails loudly the day someone adds a Date, a Map or an undefined field to a record that was previously plain.
import { test } from "node:test";
import assert from "node:assert/strict";
const roundTrip = (value) => JSON.parse(JSON.stringify(value));
test("plain records survive", () => {
const record = { id: 1, tags: ["a"], meta: { ok: true } };
assert.deepEqual(roundTrip(record), record);
});
test("a date becomes a string and an undefined field vanishes", () => {
const record = { when: new Date(0), note: undefined };
assert.deepEqual(roundTrip(record), { when: "1970-01-01T00:00:00.000Z" });
});Run it with node --test on Node.js 24. The second test documents the loss as expected behavior, so a reader who sees a date arrive as a string knows it was designed. If it was not, the test is where the decision gets made: restore dates in a reviver, or change the field's type to a string at the source.
Where JSON stops being the right format
If you need dates, maps, sets, binary data, cycles or exact large numbers, JSON needs conventions layered on top, and a different format or a schema may fit better. If the payload is large and parsed often, the cost of parsing text is real, and binary formats are smaller and faster. If humans edit the file, JSON's lack of comments and trailing commas is a burden, and a format such as JSONC, YAML or TOML is friendlier, with the cost of a parser dependency.
The parsing rules are defined in the specification under JSON, the grammar is in RFC 8259, and MDN's pages for JSON.stringify and JSON.parse list the options.


