Big numbers in JSON: BigInt, precision and JSON.parse
Updated
JSON.parse('{"id":12345678901234567890}') returns 12345678901234567000. No error, no warning, just different digits. This guide explains where the 2^53 limit comes from, why 1.10 comes back as 1.1, what “Do not know how to serialize a BigInt” means, and how to read and write big numbers exactly in JavaScript, Python, Go and Java.
Why JSON.parse changes big numbers
JSON itself sets no limit: in RFC 8259 a number is digits, an optional fraction and an optional exponent. The limit belongs to the reader. JavaScript has one number type, a 64-bit binary floating-point value (double precision) with 53 bits for the digits. Every integer up to 2^53 = 9,007,199,254,740,992 fits exactly. Above it only every second integer exists, then every fourth, and so on; JSON.parse takes the nearest one and moves on.
JSON.parse('9007199254740993'); // 9007199254740992
JSON.parse('{"id":12345678901234567890}'); // { id: 12345678901234567000 }
Number.MAX_SAFE_INTEGER; // 9007199254740991, that is 2 ** 53 - 1
Number.isSafeInteger(2 ** 53); // falseRFC 8259, section 6 lets parsers “set limits on the range and precision of numbers accepted” and promises agreement only for integers from −2^53 + 1 to 2^53 − 1: those “are interoperable in the sense that implementations will agree exactly on their numeric values”. A bigger number is still valid JSON, but two readers may see two different values.
The usual victims are 64-bit database IDs, snowflake-style IDs from distributed systems, nanosecond timestamps and amounts in minor units. Twitter’s API sent each ID twice, as the number id and the string id_str, for exactly this reason.
Why 1.10 becomes 1.1
Digits are not the only loss. A parsed number is a value, not text: 1.10 and 1.1 are the same double, so a round trip through JSON.parse and JSON.stringify prints the shortest form. 2.50 becomes 2.5, 1e3 becomes 1000, -0 becomes 0.
For most data that’s harmless. It isn’t when the text itself matters: a signature or a hash over the body stops matching, a price loses the trailing zero an invoice template expects, and a diff of two dumps shows changes nobody made. Arithmetic is a separate problem: 0.1 + 0.2 is 0.30000000000000004 in every language that uses doubles, so money belongs in a decimal type or in integer cents.
How common parsers print the same numbers
Run this yourself. The document has a big integer, two decimals with trailing zeros and an exponent:
doc='{"id":12345678901234567890,"price":1.10,"total":2.50,"exp":1e3}'
node -e 'console.log(JSON.stringify(JSON.parse(process.argv[1])))' "$doc"
# {"id":12345678901234567000,"price":1.1,"total":2.5,"exp":1000}
python3 -c 'import json, sys; print(json.dumps(json.loads(sys.argv[1])))' "$doc"
# {"id": 12345678901234567890, "price": 1.1, "total": 2.5, "exp": 1000.0}
echo "$doc" | jq -c .
# {"id":12345678901234567890,"price":1.10,"total":2.50,"exp":1E+3}The same document through common parsers with default settings:
| Parser | 12345678901234567890 | 1.10 | 1e3 |
|---|---|---|---|
JavaScript JSON.parse (Node.js 25) | 12345678901234567000 | 1.1 | 1000 |
Python json (3.9) | 12345678901234567890 | 1.1 | 1000.0 |
Go encoding/json into any (1.25) | 12345678901234567000 | 1.1 | 1000 |
Go with Decoder.UseNumber() | 12345678901234567890 | 1.10 | 1e3 |
Jackson readTree (2.15) | 12345678901234567890 | 1.1 | 1000.0 |
| jq (1.7.1) | 12345678901234567890 | 1.10 | 1E+3 |
| JSON Statham Formatter | 12345678901234567890 | 1.10 | 1e3 |
jq 1.7 keeps a number’s text while nothing touches it; arithmetic turns it into a double, so .id + 1 prints 12345678901234567000 (jq manual).
TypeError: Do not know how to serialize a BigInt
BigInt holds integers of any size, but JSON.stringify refuses it. The message depends on the engine:
- Chrome, Edge and Node.js (V8):
TypeError: Do not know how to serialize a BigInt - Firefox:
TypeError: BigInt value can’t be serialized in JSON - Safari:
TypeError: JSON.stringify cannot serialize BigInt.
The refusal is deliberate (see the error reference): a BigInt written as a plain number would come back from JSON.parse rounded, so the language makes you choose a format. Pass a replacer:
const order = { id: 12345678901234567890n, qty: 3 };
// Exact digits, as a JSON number
JSON.stringify(order, (key, value) =>
typeof value === 'bigint' ? JSON.rawJSON(value.toString()) : value);
// '{"id":12345678901234567890,"qty":3}'
// As a string: works in every runtime
JSON.stringify(order, (key, value) =>
typeof value === 'bigint' ? value.toString() : value);
// '{"id":"12345678901234567890","qty":3}'JSON.rawJSON writes the digits as a real JSON number; it works in Chrome 114+, Firefox 135+, Safari 18.4+ and Node.js 21+. The string form works everywhere, and the reader knows it has to parse it. Setting BigInt.prototype.toJSON does the same globally, for every library in the process; a replacer keeps the decision local.
Parse big numbers exactly in JavaScript
The same engines pass a third argument to the reviver of JSON.parse: context.source, the original text of each primitive value. It comes from the JSON.parse source text access proposal, now part of the ECMAScript specification together with JSON.rawJSON. Keep safe integers as numbers and turn the rest into BigInt:
const text = '{"id":12345678901234567890,"price":1.10,"qty":3}';
const data = JSON.parse(text, (key, value, context) => {
if (typeof value === 'number' && /^-?\d+$/.test(context.source)) {
return Number.isSafeInteger(value) ? value : BigInt(context.source);
}
return value;
});
data.id; // 12345678901234567890n
data.price; // 1.1 (the text said 1.10: keep context.source if that matters)
data.qty; // 3For decimals, return context.source itself, a string, when trailing zeros matter, or hand it to a decimal library. On older runtimes use the json-bigint package: it returns BigInt for big integers and writes them back as numbers, but it doesn’t keep notation, so 1.10 still comes back as 1.1 (json-bigint 1.0.0).
import JSONbig from 'json-bigint';
const parser = JSONbig({ useNativeBigInt: true });
const data = parser.parse('{"id":12345678901234567890,"price":1.10}');
data.id; // 12345678901234567890n
parser.stringify(data); // '{"id":12345678901234567890,"price":1.1}'Python, Go and Java
Python
Python’s int has no size limit, so json.loads keeps big integers exact. Decimals become float: 1.10 turns into 1.1, and 1e3 into 1000.0. The parse_float=Decimal hook keeps every digit. The standard library can’t write a Decimal back as a number, but simplejson can:
import json
from decimal import Decimal
text = '{"id": 12345678901234567890, "price": 1.10}'
data = json.loads(text, parse_float=Decimal)
data["id"] # 12345678901234567890, an exact int
data["price"] # Decimal('1.10')
json.dumps(data)
# TypeError: Object of type Decimal is not JSON serializable
import simplejson
simplejson.dumps(data) # '{"id": 12345678901234567890, "price": 1.10}'One more trap: json.loads("1e400") gives inf, and json.dumps writes it as Infinity, which is not JSON. Pass allow_nan=False to get a ValueError instead; see invalid literals.
Go
Decoding into any turns every number into a float64. Decoder.UseNumber keeps the text as json.Number, and json.Marshal writes it back unchanged. In structs, use *big.Int, uint64 or json.Number; an int64 field rejects the value with json: cannot unmarshal number 12345678901234567890 into Go struct field Order.id of type int64.
dec := json.NewDecoder(strings.NewReader(`{"id":12345678901234567890,"price":1.10}`))
dec.UseNumber()
var data map[string]any
if err := dec.Decode(&data); err != nil {
log.Fatal(err)
}
fmt.Println(data["id"], data["price"]) // 12345678901234567890 1.10
out, _ := json.Marshal(data)
fmt.Println(string(out)) // {"id":12345678901234567890,"price":1.10}
type Order struct {
ID *big.Int `json:"id"`
Price json.Number `json:"price"`
}Java (Jackson)
Jackson reads integers that don’t fit in a long as BigInteger, exactly. Decimals become double unless the target type says otherwise: declare BigDecimal and 1.10 stays 1.10, on the way out too. For untyped maps, enable DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS (deserialization features). A JsonNode tree in Jackson 2.15 strips trailing zeros even then, turning 1.10 into 1.1, unless you also disable JsonNodeFeature.STRIP_TRAILING_BIGDECIMAL_ZEROES; typed fields are simpler.
public record Order(BigInteger id, BigDecimal price) {}
Order order = new ObjectMapper().readValue(
"{\"id\":12345678901234567890,\"price\":1.10}", Order.class);
order.id(); // 12345678901234567890
order.price(); // 1.10What JSON Statham does with numbers
The tools on this site never turn your document into JavaScript numbers. The API reads the text and copies each number as written, so none of the above depends on a setting:
- The Formatter and the Minifier change whitespace only:
12345678901234567890,1.10and1e3come out as they went in. - The Validator counts big integers in its report as
big_ints: integers beyond 2^53 − 1 thatJSON.parsewould round. - Diff compares numbers by exact decimal value:
1.10equals1.1and1e3equals1000, but9007199254740993and9007199254740992are different. - JSON to YAML writes every number with the same digits.
- JSON to query string copies numbers as written; in the other direction, with Types switched to numbers,
2.50stays2.50.
After Format, Minify and JSON to YAML, the status bar on a wide screen also says how many big integers came through, for example “1 big int, exact”. To see it, paste the document from the example above into the Formatter, or open its Sample menu and pick Precision test.
How to send big numbers safely
- IDs: send 64-bit IDs as strings. They are labels, not quantities, and every client can read a string.
- Money: send a decimal string such as
"19.90", or integer minor units that stay below 2^53 − 1, and say which in the API docs. - Signed or hashed bodies: sign the exact bytes you send, and don’t parse and re-serialize them on the way.
- Pipelines: check what each hop does with numbers. One
JSON.parsein a proxy or a logger is enough to change a value.
Big numbers in JSON FAQ
Is 12345678901234567890 valid JSON?
Yes. RFC 8259 puts no limit on the size of a number and lets each parser choose its own. The Validator accepts it and counts it in big_ints.
What is the largest integer JSON.parse keeps exactly?
9007199254740991, which is Number.MAX_SAFE_INTEGER or 2^53 − 1. Some bigger integers survive by luck, powers of two for example, but Number.isSafeInteger returns true only up to that value.
Should an API send 64-bit IDs as strings?
If any client is JavaScript, yes. A number above 2^53 − 1 is valid JSON, but a browser reads a different value and doesn’t say so.
Why does JSON.stringify throw on BigInt but not on big numbers?
A big Number is already rounded by the time it reaches JSON.stringify, so nothing is left to lose. A BigInt still has every digit, and a plain JSON number would lose them on the next JSON.parse, so the engine makes you choose: JSON.rawJSON or a string.