JSON in JavaScript: JSON.stringify and JSON.parse, Replacers, Revivers and Pitfalls
JSON in JavaScript: the format's strict rules, JSON.stringify and JSON.parse, what happens to undefined, NaN, dates, Maps, BigInt and cycles, pretty-printing, replacers, toJSON, revivers, safe parsing and large numbers with JSON.rawJSON.
kvi5hnuCode Sprout team member7 min readOn this page
JSON (JavaScript Object Notation) is the most widely used data format on the web. APIs send and receive it, package.json and countless configuration files use it, browsers store it in localStorage, and databases index it. Its syntax was borrowed from JavaScript's object and array literals, but it's a separate, much stricter language understood by every programming language.
JavaScript converts between its values and JSON text with two functions: JSON.stringify (serializing: value → string) and JSON.parse (parsing: string → value).
const order = { id: 42, items: ["pen", "ink"], paid: false, coupon: null };
const text = JSON.stringify(order);
console.log(text, typeof text);
const back = JSON.parse(text);
console.log(back.items[1], back === order);
{"id":42,"items":["pen","ink"],"paid":false,"coupon":null} string
ink false
The JSON format
JSON has only six kinds of values: objects, arrays, strings, numbers, true/false and null. Compared with JavaScript literals, it's strict:
- Property names must be in double quotes:
{"a": 1}, never{a: 1}or{'a': 1}. - Strings use double quotes only, and control characters like tabs and newlines must be escaped (
\t,\n). - No trailing commas, no comments, no leading zeros (
01), noNaN,Infinityorundefined. - Whitespace between tokens is allowed and ignored.
const attempts = ["{'a':1}", "{a:1}", '{"a":1,}', "[1,2,]", '{"a":01}', "NaN", "// note\n1", ""];
for (const text of attempts) {
try {
JSON.parse(text);
} catch (err) {
console.log(JSON.stringify(text).padEnd(12), err.name);
}
}
"{'a':1}" SyntaxError
"{a:1}" SyntaxError
"{\"a\":1,}" SyntaxError
"[1,2,]" SyntaxError
"{\"a\":01}" SyntaxError
"NaN" SyntaxError
"// note\n1" SyntaxError
"" SyntaxError
The top-level value doesn't have to be an object: "42", "true" and '"text"' are valid JSON too. Formats like JSON5 and JSONC (used by VS Code and TypeScript's tsconfig.json) relax the rules to allow comments and trailing commas, but JSON.parse doesn't accept them.
JSON.stringify: what survives
JSON has fewer types than JavaScript, so JSON.stringify has to decide what to do with everything else:

const sample = {
missing: undefined,
method() {},
tag: Symbol("t"),
ratio: NaN,
limit: -Infinity,
created: new Date(0),
pattern: /ab+c/g,
lookup: new Map([["a", 1]]),
unique: new Set([1]),
};
console.log(JSON.stringify(sample));
console.log(JSON.stringify([undefined, () => 1, Symbol("s"), NaN]));
console.log(JSON.stringify(undefined), JSON.stringify(() => 1));
{"ratio":null,"limit":null,"created":"1970-01-01T00:00:00.000Z","pattern":{},"lookup":{},"unique":{}}
[null,null,null,null]
undefined undefined
The rules worth memorizing:
undefined, functions and symbols are left out of objects, becomenullin arrays (to keep positions), and makeJSON.stringifyreturnundefined(not a string) at the top level.NaNand±Infinitybecomenull.- Dates become ISO strings, through their
toJSONmethod. Parsing doesn't turn them back into dates. Map,Set,RegExpandErrorbecome{}: their contents aren't stored in own enumerable properties. Convert them first:Object.fromEntries(map),[...set].- Only own enumerable string-keyed properties are included: no inherited ones, no symbol keys, no non-enumerable ones. Getters are called and their values included.
And two values make it throw a TypeError:
try {
JSON.stringify({ total: 10n });
} catch (err) {
console.log("BigInt:", err.name);
}
const node = { name: "root" };
node.self = node;
try {
JSON.stringify(node);
} catch (err) {
console.log("cycle:", err.name);
}
BigInt: TypeError
cycle: TypeError
JSON.parse(JSON.stringify(x)) was once the standard deep-copy trick. Given everything above, it silently corrupts dates, maps, sets, undefined and special numbers. Use structuredClone for copies (article 21) and JSON for data exchange.
Pretty-printing
The third argument adds indentation: a number of spaces (up to 10), or a string such as "\t":
console.log(JSON.stringify({ team: "core", members: ["Ana", "Bo"] }, null, 2));
{
"team": "core",
"members": [
"Ana",
"Bo"
]
}
Use it for files people read (config, test fixtures, logs while debugging); send compact JSON over the network.
Customizing stringify
Choosing properties with an array
If the second argument is an array of names, only those properties are included, in that order, at every level:
const user = { id: 1, name: "Ana", password: "hunter2", role: "dev" };
console.log(JSON.stringify(user, ["role", "id"]));
{"role":"dev","id":1}
Transforming values with a replacer function
If the second argument is a function (key, value) => newValue, it's called for every value, and its result is serialized instead. Returning undefined removes the property:
const account = { id: 1, password: "x", profile: { password: "y", public: true } };
console.log(JSON.stringify(account, (key, value) => (key === "password" ? undefined : value)));
const invoice = { total: 12345678901234567890n, lines: 3 };
console.log(JSON.stringify(invoice, (key, value) => (typeof value === "bigint" ? value.toString() : value)));
{"id":1,"profile":{"public":true}}
{"total":"12345678901234567890","lines":3}
The replacer is first called with the key "" and the whole value, and this is the object containing the current property.
toJSON: an object decides how it's serialized
If a value has a toJSON method, JSON.stringify calls it and serializes the result instead. That's how dates produce ISO strings, and you can do the same for your own objects:
const price = {
cents: 1999,
currency: "EUR",
toJSON() {
return { amount: (this.cents / 100).toFixed(2), currency: this.currency };
},
};
console.log(JSON.stringify({ item: "lamp", price }));
{"item":"lamp","price":{"amount":"19.99","currency":"EUR"}}
toJSON receives the property key as its argument. The order of operations is: toJSON first, then the replacer.
JSON.parse and revivers
JSON.parse(text) returns a fresh value built from the text. Duplicate keys are allowed, and the last one wins. Numbers are converted to ordinary JavaScript numbers.
An optional reviver function (key, value) => newValue lets you transform values while parsing. It's called for every value, from the innermost outwards, ending with the root under the key "". Returning undefined removes the property:
const text = '{"title":"Launch","when":"2026-03-01T09:30:00.000Z","_internal":7}';
const isoDate = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
const event = JSON.parse(text, (key, value) => {
if (key.startsWith("_")) return undefined;
if (typeof value === "string" && isoDate.test(value)) return new Date(value);
return value;
});
console.log(event.when instanceof Date, event.when.getUTCHours(), Object.keys(event));
const visited = [];
JSON.parse('{"a":[1,{"b":2}],"c":3}', (key, value) => {
visited.push(key === "" ? "(root)" : key);
return value;
});
console.log(visited.join(" "));
true 9 [ 'title', 'when' ]
0 b 1 a c (root)
The second output shows the order: array element 0, then b inside the nested object, then that object itself (key 1), then the array a, then c, and the root last.
Whenever you add toJSON methods or replacers that change types, you're defining your own format, and you'll need a matching reviver to get the original structure back. Every other program reading the data needs to know about it too.
Validate what you parse
JSON.parse only checks syntax. The result is whatever the text said, so data from a network, a file or localStorage should be validated before you trust its shape: wrap parsing in try/catch, then check types, or use a schema library (Zod, Valibot, Ajv) or TypeScript type guards.
function readSettings(text) {
try {
const data = JSON.parse(text);
return typeof data === "object" && data !== null && !Array.isArray(data) ? data : {};
} catch {
return {};
}
}
console.log(readSettings('{"theme":"dark"}'), readSettings("oops"), readSettings("[1,2]"));
{ theme: 'dark' } {} {}
Never parse JSON with eval (article 36). JSON.parse can't run code; eval runs whatever an attacker put in the text.
Large numbers: precision loss and JSON.rawJSON
JSON numbers can have any number of digits, but JSON.parse turns them into 64-bit floating-point numbers, so integers above Number.MAX_SAFE_INTEGER (article 10) lose precision. This happens in practice with database IDs and Twitter/X-style snowflake IDs:
console.log(JSON.parse('{"id": 12345678901234567890}').id);
12345678901234567000
The common fix is for APIs to send such IDs as strings. A newer feature, standardized in ES2026 and already available in Chrome, Firefox and Node.js, gives you the exact source text:
// The reviver's third argument holds the original text of primitive values
const data = JSON.parse('{"id": 12345678901234567890}', (key, value, context) =>
key === "id" ? BigInt(context.source) : value,
);
data.id; // 12345678901234567890n
// JSON.rawJSON emits text exactly as given
JSON.stringify({ id: JSON.rawJSON("12345678901234567890") }); // '{"id":12345678901234567890}'
Common questions
Is JSON the same as a JavaScript object?
No. JSON is text in a specific format; a JavaScript object is a value in memory. "Parse the JSON" means converting text into an object. Not every object literal is valid JSON (unquoted keys, single quotes, functions), and not every JavaScript value can be represented in JSON.
How do I store a Map or Set as JSON?
Convert it to something JSON supports: JSON.stringify([...map]) (an array of pairs) or JSON.stringify(Object.fromEntries(map)) for string keys, and [...set] for sets. Rebuild with new Map(JSON.parse(text)) or new Set(JSON.parse(text)).
Does JSON.stringify keep property order?
It uses the normal own-key order: integer-like keys first in ascending order, then other keys in insertion order (article 48). Two objects with the same data but keys added in different orders produce different strings, so don't compare objects by their JSON.
Why does fetch have response.json()?
It's a shortcut that reads the response body as text and then calls JSON.parse on it, returning a promise (part 15). It throws a SyntaxError if the body isn't valid JSON, for example an HTML error page.
Summary
- JSON is a strict text format: double-quoted keys and strings, no comments, no trailing commas, no
undefined,NaNorInfinity. JSON.stringifydropsundefined, functions and symbols from objects (nullin arrays), turnsNaN/Infinityintonull, dates into ISO strings, andMap/Set/RegExp/Errorinto{}; it throws on BigInt and cycles.- The third argument pretty-prints; the second is an allowlist array or a replacer function;
toJSONlets an object choose its own representation. JSON.parsethrows aSyntaxErroron invalid text; its reviver runs for every value, innermost first, root last.- Parse defensively and validate the result; never use
eval. - Large integers lose precision when parsed; send them as strings, or use the reviver's
context.sourceandJSON.rawJSON.
Practice Questions
What does this print?
console.log(JSON.stringify({ a: undefined, b: [undefined], c: null }));
Answer
{"b":[null],"c":null}. undefined is left out as a property value but becomes null inside an array; null is valid JSON.
What does this expression return?
typeof JSON.parse(JSON.stringify({ when: new Date(0) })).when
Answer
"string". The date is serialized as an ISO string through Date.prototype.toJSON, and JSON.parse has no way of knowing it was a date. Use a reviver to restore it.
Serialize this object without any token properties, at any depth:
{ user: "ana", token: "abc", meta: { token: "def" } }
Answer
JSON.stringify(obj, (key, value) => (key === "token" ? undefined : value))
Gives {"user":"ana","meta":{}}. The replacer runs for nested properties too.
Why does this code throw, and what's the valid JSON?
JSON.parse("{name: 'Ana'}")
Answer
JSON requires double-quoted property names and double-quoted strings. The valid text is {"name": "Ana"}.
Previous: Copying and Merging Objects in JavaScript: Object.assign, Spread, Defaults and Deep Merge
Next: JavaScript Object Methods: toString, toLocaleString, valueOf and toJSON

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.