JSON — what JSON.stringify drops, changes and refuses¶
Level: 201 · for anyone who has saved an object with JSON.stringify and read it back
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: JSON.stringify drops undefined, functions and symbols from objects and writes them as null in arrays, turns NaN and Infinity into null, a Date into a string and a Map into {}, and throws a TypeError on a BigInt or a cycle.
Keywords: JSON.stringify, JSON.parse, toJSON
What the finished page will answer¶
- What does
JSON.stringifywrite forundefined, a function, a symbol,NaN,-Infinity, aDateand aMap, inside an object and inside an array? - What does it throw for a
BigIntand for a cycle, and how do a replacer function and atoJSONmethod get around each? - What does
JSON.parse(JSON.stringify(x))give back for aDate, and how does a reviver turn it back into one? - What does
JSON.stringify(undefined)return, and what doesJSON.stringifywrite for a string holding a lone surrogate such as U+D800? - What does
JSON.parsedo with duplicate keys and with a"__proto__"key? - How does
JSON.rawJSONwrite aBigIntlarger than 2^53 as a bare number, and which Node versions have it?
Examples it will need¶
-
json_stringify_drops_js.js— one object holding undefined, a function, a symbol, NaN, -Infinity, a Date and a Map, stringified, then the same values inside an array -
json_stringify_refuses_js.js— the TypeError for a BigInt and for a cycle, then the BigInt written through a replacer, toJSON and JSON.rawJSON -
json_round_trip_dates_js.js— a Date that comes back from JSON.parse as a string, then as a Date again through a reviver
See also¶
- Copying objects — structuredClone keeps what JSON drops
- BigInt — the type JSON.stringify refuses
- External data — the any that JSON.parse returns
- Strings and bytes — lone surrogates, which stringify escapes
- Formatting dates — toISOString, which a Date's toJSON calls
- Rust: The round trip ↗ — the round-trip test that catches what serialization drops
- Encodings: UTF-16 and surrogates ↗ — where the lone surrogates that stringify escapes come from