Sub topic 3
Controlling Serialization with toJSON
This chapter assumes you know JSON.stringify, JSON.parse, replacers, and how stringify drops or converts unsupported values. It covers six topics: customizing output, restoring types, and the limits you will run into.
Controlling Serialization with toJSON
If a value has a toJSON method, stringify serializes whatever that method returns. Date already works this way, which is why dates come out as ISO strings.
class Money {
constructor(cents, currency) {
this.cents = cents;
this.currency = currency;
}
toJSON() {
return { amount: this.cents / 100, currency: this.currency };
}
}
console.log(JSON.stringify({ price: new Money(1999, "EUR") }));
// {"price":{"amount":19.99,"currency":"EUR"}}Rebuilding Dates and Custom Types with a Reviver
Parsing never turns strings back into Date objects. A reviver is a function passed as the second argument to parse. It runs on every key/value pair, so it can do that conversion for you.
const json = '{"name":"launch","at":"2024-01-15T09:30:00.000Z"}';
const isoDate = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
const event = JSON.parse(json, (key, value) =>
typeof value === "string" && isoDate.test(value) ? new Date(value) : value
);
console.log(event.at instanceof Date); // trueDealing with Circular References
If an object refers back to itself, stringify throws a TypeError. A replacer that tracks the objects it has already seen can swap repeats for a marker:
function circularReplacer() {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) return "[Circular]";
seen.add(value);
}
return value;
};
}
const node = { name: "a" };
node.self = node;
console.log(JSON.stringify(node, circularReplacer()));
// {"name":"a","self":"[Circular]"}BigInt Errors and Large-Number Precision Loss
JSON numbers are parsed as doubles. Integers above Number.MAX_SAFE_INTEGER lose precision, and stringify throws on BigInt values:
console.log(JSON.parse('{"id": 9007199254740993}').id); // 9007199254740992
const out = JSON.stringify({ n: 10n }, (k, v) =>
typeof v === "bigint" ? v.toString() : v
);
console.log(out); // {"n":"10"}Send large IDs as strings.
JSON Round-Trip Cloning Versus structuredClone
| Feature | `JSON.parse(JSON.stringify(x))` | `structuredClone(x)` |
|---|---|---|
| Dates | Become strings | Preserved |
| Map / Set | Become `{}` | Preserved |
| Cycles | Throw | Supported |
| Functions | Dropped | Throw |
Use structuredClone for deep copies. Use the JSON round trip only when you want the JSON-shaped result.
Parsing Untrusted JSON Safely
- Wrap
parseintry/catchand treat aSyntaxErroras bad input. - Never use
evalon JSON text. - Check the parsed structure against a schema before you use it.
- Do not deep-merge parsed objects into existing ones without filtering out
__proto__. Otherwise an attacker can polluteObject.prototype. - Limit the request body size before you parse it.
Exercise
An API returns {"orderId": 12345678901234567890}. What does JSON.parse give for orderId, and how should the API be changed?
Show answer
You get a rounded double, 12345678901234567000, not the exact value. The API should send the ID as a string, "12345678901234567890". The client can then keep it as a string or convert it with BigInt().