How to Parse BigInt in JSON (Without Losing Precision)
Here is a scary fact: JavaScript cannot handle 64-bit integers natively in JSON.
If your API sends a user ID like 9223372036854775807 (the max value of a 64-bit integer), and you do:
const data = JSON.parse('{"id": 9223372036854775807}');
console.log(data.id);
// Output: 9223372036854776000 (Wait, what?)
It rounded it. Your ID is wrong. Your database update will fail. Your user is 404.
Why? Because JSON.parse converts numbers to JavaScript Number type, which is a double-precision float. It only has 53 bits of precision. Anything larger gets rounded.
In this guide, we'll show you how to solve this problem for good. (And yes, our JSON Formatter handles BigInts correctly).
The Solution: JSON-BigInt
Since JSON.parse is broken for large numbers, you need a parser that reads numbers as strings or native BigInts.
1. The "String Trick" (Server-Side Fix)
If you control the API, the easiest fix is to send the ID as a string.
// Bad
{ "id": 9223372036854775807 }
// Good
{ "id": "9223372036854775807" }
2. Client-Side Libraries
If you cannot change the API, you need a custom parser. The most popular library is json-bigint.
npm install json-bigint
import JSONBig from 'json-bigint';
const json = '{"id": 9223372036854775807}';
const data = JSONBig.parse(json);
console.log(data.id.toString());
// Output: "9223372036854775807" (Correct!)
3. Native BigInt in Modern JS
Modern browsers now support BigInt. You can write a custom reviver function for JSON.parse, but unfortunately, the reviver is called after the number has already been parsed (and corrupted).
So, you cannot use JSON.parse's reviver to fix this. You must use a text-based parser like json-bigint.
Visualizing the Problem
If you are debugging an API and suspect precision loss, paste the raw response into our JSON Formatter. We use a lossless parser that highlights BigInts, so you can see exactly what the server sent vs. what JS sees.
Summary
- JavaScript
Numbertypes are unsafe for IDs larger than2^53 - 1. JSON.parsecorrupts these numbers silently.- Use string IDs on the server or libraries like
json-biginton the client.
Related Articles in This Series
This post is part of our Complete JSON Guide for Web Developers. Explore related topics:
Found this helpful?
Join thousands of developers using our tools to write better code, faster.