Sub topic 11
BigInt Errors and Large-Number Precision Loss
This chapter assumes you know JavaScript number types, including BigInt literals such as 10n, and that you have read the earlier chapters on replacers and revivers. It covers two related problems. JSON.stringify refuses to serialize BigInt values, and JSON.parse silently changes integers that are too large for a JavaScript number.
Why JSON numbers lose precision
The JSON format puts no limit on the size of a number. JSON.parse, however, turns every JSON number into a JavaScript Number. A Number is a 64-bit floating-point value (a "double"). A double can represent every integer exactly only up to Number.MAX_SAFE_INTEGER, which is 2^53 − 1, or 9007199254740991. Above that limit, parsing rounds the number to the nearest double it can represent, and it does so without any warning.
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
const parsed = JSON.parse('{"id": 9007199254740993}');
console.log(parsed.id); // 9007199254740992
console.log(Number.isSafeInteger(parsed.id)); // falseThis causes real bugs with database IDs, snowflake IDs, and financial amounts stored in the smallest currency unit. Two different IDs can parse to the same number, so a lookup returns the wrong record.
Why stringify throws on BigInt
BigInt values can hold integers of any size. JSON has no BigInt type, and the language designers chose to throw an error instead of guessing a representation. If they had written a BigInt as a plain JSON number, any standard parser would round it again on the way back in.
try {
JSON.stringify({ balance: 10n });
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // wording varies by engine
}Node.js reports "Do not know how to serialize a BigInt", and Firefox reports "BigInt value can't be serialized in JSON". Don't match on the message text. Check for TypeError instead.
The working pattern: strings on the wire
The most reliable approach is to send large integers as JSON strings. Strings pass through every JSON parser unchanged, and you convert them back to BigInt only for the fields you know hold one.
const BIGINT_KEYS = new Set(["id", "balance"]);
function toJson(value) {
return JSON.stringify(value, (key, v) =>
typeof v === "bigint" ? v.toString() : v
);
}
function fromJson(text) {
return JSON.parse(text, (key, v) =>
BIGINT_KEYS.has(key) && typeof v === "string" && /^-?\d+$/.test(v)
? BigInt(v)
: v
);
}
const text = toJson({ id: 9007199254740993n, balance: 42n, name: "Ada" });
console.log(text); // {"id":"9007199254740993","balance":"42","name":"Ada"}
const back = fromJson(text);
console.log(back.id); // 9007199254740993n
console.log(typeof back.balance); // "bigint"
console.log(back.name); // "Ada"The reviver checks key names on purpose. If it converted every string made of digits, it would also turn zip codes, phone numbers, and similar fields into BigInt values.
Common mistakes
| Mistake | What happens | Better choice |
|---|---|---|
| Defining `BigInt.prototype.toJSON` globally | Every library in the process changes behavior | Use a replacer scoped to your own call |
| Converting to `BigInt` in a reviver | Precision is already gone | Have the server send IDs as strings |
| Writing a replacer that returns `Number(v)` | Large values round on output | Return `v.toString()` |
| Assuming the API's numeric IDs are safe | Rare, hard-to-reproduce bugs appear | Check with `Number.isSafeInteger` |
Exercise
A server returns {"orderId": 12345678901234567890}. You write JSON.parse(text, (k, v) => k === "orderId" ? BigInt(v) : v). Will orderId hold the exact value? Explain why or why not.
Show answer
No. JSON.parse converts the number to a double before the reviver runs, so the reviver receives an already-rounded Number, and BigInt(v) keeps that rounded value. The fix is for the server to send orderId as a string, such as "12345678901234567890", and then the reviver can call BigInt on the string.
Exercise
Why does JSON.stringify({ n: 10n }, (k, v) => typeof v === "bigint" ? Number(v) : v) work for 10n but count as a bug in general?
Show answer
Number(v) converts the BigInt to a double. For values above Number.MAXSAFEINTEGER, that conversion rounds, so the output is wrong even though no error is thrown. Converting with v.toString() keeps every digit.