Sub topic 11
BigInt Errors and Large-Number Precision Loss
JSON has a single number type and puts no limit on its size or precision. JavaScript reads every JSON number into a Number, which is a 64-bit IEEE 754 double. Most of the time the two fit together without trouble. They stop fitting in two cases: an integer too large for a double, and a BigInt that JSON.stringify will not accept at all. This chapter covers both failures, explains the cause of each, and walks through the fixes and their trade-offs.
This chapter assumes you already know how replacers, toJSON, and revivers work from earlier chapters. You should also know that BigInt is JavaScript's arbitrary-precision integer type, written with an n suffix (10n).
The Two Problems at a Glance
The first problem happens on output. JSON.stringify throws a TypeError when it reaches a BigInt. It does not drop the value or turn it into null, as it does with functions or undefined. The whole call fails.
The second problem happens on input, and you get no error at all. JSON.parse turns a large integer into the nearest double it can represent. The number you get back may differ from the one in the text, and nothing tells you.
console.log(JSON.parse('{"id": 9007199254740993}').id);
// 9007199254740992 (precision lost beyond Number.MAX_SAFE_INTEGER)
// JSON.stringify({ n: 10n }); // throws TypeError: BigInt value can't be serialized
const out = JSON.stringify({ n: 10n }, (key, value) =>
typeof value === "bigint" ? value.toString() : value
);
console.log(out); // {"n":"10"}The exact error text depends on the engine. V8 (Node.js and Chrome) reports TypeError: Do not know how to serialize a BigInt. Firefox reports BigInt value can't be serialized in JSON. Code should check err instanceof TypeError and should not match on the message.
Why Large Integers Lose Precision
A double stores 53 bits of significand. Every integer from −(2^53 − 1) to 2^53 − 1 can be stored exactly. JavaScript exposes the limits as Number.MAX_SAFE_INTEGER (9007199254740991) and Number.MIN_SAFE_INTEGER. Above that range, representable doubles are spaced more than 1 apart. Between 2^53 and 2^54 only even integers exist, so 9007199254740993 rounds to 9007199254740992.
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
console.log(Number.isSafeInteger(9007199254740991)); // true
console.log(Number.isSafeInteger(9007199254740992)); // false
// Two different JSON texts produce the same Number:
const a = JSON.parse("9007199254740992");
const b = JSON.parse("9007199254740993");
console.log(a === b); // trueJSON.parse follows the specification here. It reads the digits and converts them with the same rules as a numeric literal in source code. Writing 9007199254740993 directly in a .js file gives the same rounded value.
Where this bites in practice
The usual victims are IDs produced by other systems:
- Snowflake-style IDs from Twitter/X, Discord, and many internal services are 64-bit integers and often exceed 2^53.
- Database
BIGINTprimary keys are safe only while they stay small. - Financial systems that send amounts in the smallest currency unit, and nanosecond timestamps, can pass 2^53.
An ID that is wrong by one is worse than a crash. The code fetches, updates, or deletes the wrong record and keeps running. For this reason many APIs send 64-bit IDs as both a number and a string. Twitter's API, for example, sends id and id_str.
Other numeric edge cases
The integer limit is the most common problem, but JSON numbers have a few more quirks in JavaScript:
| JSON text or value | Result | Notes |
|---|---|---|
| `JSON.parse("1e400")` | `Infinity` | Overflow becomes `Infinity`, which cannot be stringified back (it becomes `null`) |
| `JSON.parse("0.1")` | `0.1` (approximate) | Binary floating point cannot store most decimal fractions exactly |
| `JSON.stringify(-0)` | `"0"` | The sign of zero is lost |
| `JSON.stringify(1e21)` | `"1e+21"` | Large numbers are written in exponent form |
| `JSON.parse("1.0")` | `1` | JSON does not keep the difference between integer and decimal |
Money is the classic decimal problem. Send amounts as integer minor units (cents) when they fit within the safe range. Otherwise send them as decimal strings and handle them with a decimal library.
How Stringify Reaches the BigInt Error
You need to know the order in which JSON.stringify processes each value, because that order decides which fixes work. For each property, it does the following:
- If the value is an object or a
BigInt, it looks for atoJSONmethod and calls it if one exists. - If a replacer function was passed, it calls the replacer with the result.
- If the value is still a
BigIntat that point, it throws.
Both toJSON and the replacer run before the check, so either one can convert a BigInt safely.
Fixing Serialization: Three Options
Option 1: A replacer function
A replacer keeps the conversion local to one call and changes nothing global:
function bigintReplacer(key, value) {
return typeof value === "bigint" ? value.toString() : value;
}
const order = { id: 123456789012345678901234567890n, qty: 2 };
console.log(JSON.stringify(order, bigintReplacer));
// {"id":"123456789012345678901234567890","qty":2}The output carries the value as a string. The receiving side has to know that id is a string holding an integer. This is the most portable format, because every JSON parser in every language can read a string without losing data.
Option 2: `BigInt.prototype.toJSON`
You can add a toJSON method to the prototype, and then every JSON.stringify call accepts BigInts:
BigInt.prototype.toJSON = function () {
return this.toString();
};
console.log(JSON.stringify({ big: 42n })); // {"big":"42"}This works, but it changes a built-in object for the whole process, including inside third-party libraries. Some libraries depend on the TypeError to detect BigInts, and any of them may define its own toJSON that conflicts with yours. Use this only in application code you fully control, such as a small script or a single service entry point. Never put it in a published library.
Option 3: Emit a real JSON number with `JSON.rawJSON`
Sometimes the receiver expects a numeric literal instead of a string. A Java or Go service that reads into an int64 is a common case. Newer engines provide JSON.rawJSON(text), which returns a value that JSON.stringify writes out verbatim as a number:
const replacer = (key, value) =>
typeof value === "bigint" ? JSON.rawJSON(value.toString()) : value;
console.log(JSON.stringify({ id: 9007199254740993n }, replacer));
// {"id":9007199254740993}JSON.rawJSON comes from the "JSON.parse source text access" proposal. It is available in recent V8 (Node.js 21+, Chrome 114+) and in current Firefox and Safari. Check for it with typeof JSON.rawJSON === "function" before you rely on it. Keep in mind that any JavaScript client reading this output with a plain JSON.parse will hit the same precision loss again.
Fixing Parsing: Recovering the Digits
Strings plus a key-aware reviver
If the producer sends big integers as strings, a reviver can turn them back into BigInts. Convert by key name, not by testing whether the value looks numeric. A regex such as /^\d+$/ would also convert ZIP codes, phone numbers, and other strings that only look like integers.
const BIGINT_KEYS = new Set(["id", "parentId"]);
function bigintReviver(key, value) {
if (BIGINT_KEYS.has(key) && typeof value === "string" && /^-?\d+$/.test(value)) {
return BigInt(value);
}
return value;
}
const text = '{"id":"9007199254740993","parentId":"42","zip":"02134"}';
const rec = JSON.parse(text, bigintReviver);
console.log(rec.id); // 9007199254740993n
console.log(rec.parentId); // 42n
console.log(rec.zip); // "02134" (left alone)A reviver alone cannot fix numbers
A common mistake is to write a reviver that calls BigInt(value) on a large number. The reviver runs after the digits have been converted to a double, so the precision is already gone:
const wrong = JSON.parse('{"id": 9007199254740993}', (key, value) =>
typeof value === "number" && !Number.isSafeInteger(value) ? BigInt(value) : value
);
console.log(wrong.id); // 9007199254740992n (wrong, just as a BigInt)Reading the source text with `context.source`
The same proposal that added JSON.rawJSON gives revivers a third argument. For primitive values, context.source holds the original JSON text of the value, so the digits can still be recovered:
function preciseReviver(key, value, context) {
if (
typeof value === "number" &&
!Number.isSafeInteger(value) &&
context &&
typeof context.source === "string" &&
/^-?\d+$/.test(context.source)
) {
return BigInt(context.source);
}
return value;
}
const parsed = JSON.parse('{"id": 9007199254740993, "count": 3, "ratio": 1.5}', preciseReviver);
console.log(parsed.id); // 9007199254740993n
console.log(parsed.count); // 3
console.log(parsed.ratio); // 1.5The guard context && typeof context.source === "string" matters. Older engines pass no third argument, and the reviver then falls back to normal behavior without crashing. The /^-?\d+$/ test skips values such as 1e300, which are not integers written out in digits.
This approach gives mixed types. Small IDs stay as Number and large ones become BigInt, and 1n === 1 is false. If a field can hold either size, convert it to BigInt every time, by key, so consumers see one type.
When none of that is available
If you must support older runtimes and cannot change the producer, use a parser library that keeps large numbers, such as json-bigint or lossless-json. These libraries read the raw text themselves, so Number never touches the digits.
Choosing a Strategy
| Situation | Recommended approach |
|---|---|
| You control both ends | Send large integers as strings and revive them by key |
| You are sending to a non-JS service that expects numbers | Replacer with `JSON.rawJSON` (modern engines) |
| You are receiving numeric big IDs, modern runtime | Reviver with `context.source` |
| You are receiving numeric big IDs, old runtime | A lossless JSON parsing library |
| Quick script, no libraries involved | `BigInt.prototype.toJSON` is acceptable |
| Decimal money values | Integer minor units, or decimal strings plus a decimal library |
Exercises
Exercise
A service returns {"orderId": 18014398509481985}. You parse it with JSON.parse(text, (k, v) => k === "orderId" ? BigInt(v) : v). Will orderId be correct? Explain.
Show answer
No. 18014398509481985 is larger than 2^53, so it rounds to a nearby double (18014398509481984) before the reviver runs. Calling BigInt on that double keeps the wrong value. The fix is to read the reviver's third argument (context.source), use a lossless parser, or have the service send the ID as a string.
Exercise
Why does JSON.stringify({ n: 5n }, (k, v) => typeof v === "bigint" ? Number(v) : v) succeed, and when would this replacer be a bad idea?
Show answer
The replacer runs before stringify checks for BigInt, so the value is already a Number when the check happens, and the output is {"n":5}. The replacer is a bad idea when values can exceed Number.MAXSAFEINTEGER, because Number(v) then rounds them silently. Converting with v.toString() or JSON.rawJSON(v.toString()) keeps every digit.
Exercise
Write a reviver that converts the string fields id and ownerId to BigInt, leaves all other strings alone, and tolerates the fields being missing.
Show answer
const keys = new Set(["id", "ownerId"]); const reviver = (key, value) => keys.has(key) && typeof value === "string" && /^-?\d+$/.test(value) ? BigInt(value) : value; Missing fields never reach the reviver, so it needs no extra handling for them.