Big IDs in JSON: Why JSON.parse Rounds 64-bit Numbers

Dec 2, 2026 · 9 min read

JSON.parse rounds integers past 2^53, so 19-digit asset IDs come back changed. Fix it with string IDs, BigInt, a reviver with context.source, JSON.rawJSON.

A support ticket came in on a Monday: "The asset page shows the wrong laptop." The IT asset register had given a ThinkPad the ID 7340196284512039415, the API returned that exact number, and the browser showed 7340196284512039000. Nothing was corrupted in the database. Nothing was wrong in the API. The number was rounded by JSON.parse on the way into the page, and once it was rounded it pointed at a different record, or at nothing at all.

If you work with database keys, snowflake-style IDs, serial numbers stored as integers or anything from a 64-bit column, you will hit this sooner or later. This article explains why it happens, how to see it, and the three fixes that work: send big IDs as strings, read them with a reviver that sees the original text, and write them back with JSON.rawJSON.

Reproducing it in three lines

Here is the asset record from that ticket, parsed in Node 22. The output in the comments is what the script printed, not what I expected it to print:

js
const body = '{"assetId": 7340196284512039415, "model": "ThinkPad T14 Gen 5", "serial": "PF4X2K9Q"}';

const asset = JSON.parse(body);
console.log(asset.assetId);                        // 7340196284512039000
console.log(Number.MAX_SAFE_INTEGER);              // 9007199254740991
console.log(Number.isSafeInteger(asset.assetId));  // false

JavaScript has one number type for everyday maths: a 64-bit IEEE 754 float. It can hold every integer up to Number.MAX_SAFE_INTEGER, which is 253 - 1, or 9,007,199,254,740,991. That is 16 digits. Past it, the float only has room for some integers, so the parser picks the nearest one it can store. A 19-digit ID loses its last three or four digits.

The part that turns this from a display bug into a data bug is that different IDs round to the same value. Two laptops, two IDs that differ in the last digits, one number after parsing:

js
const a = JSON.parse('{"assetId": 7340196284512039415}').assetId;
const b = JSON.parse('{"assetId": 7340196284512039422}').assetId;

console.log(a === b);  // true: two different laptops, one number
console.log(a);        // 7340196284512039000

So a lookup by ID can return the wrong row, a Map keyed by ID silently merges two assets, and a PATCH request sent back to the server updates a record nobody meant to touch. No exception, no warning.

Is this a JSON bug?

No, and the spec says so plainly. JSON itself puts no limit on the size of a number. Section 6 of RFC 8259 notes that because most software uses IEEE 754 doubles, only integers in the range -(253)+1 to 253-1 are safe to exchange. Anything bigger is valid JSON that some readers will get wrong. Python, Go with int64, Java with long and PostgreSQL's bigint all hold the full value. The browser is usually the one that rounds.

That also means the bug only shows up at the boundary. Your server tests pass, your database looks right, and the first place the wrong number appears is a screen, a CSV export or a log line written by front-end code.

Fix 1: send big IDs as strings (the server-side habit)

The fix that works for every client, old browsers included, is to stop sending the ID as a number. An ID is a label. Nobody adds two asset IDs together, so there is no reason for it to be numeric on the wire. Large public APIs settled on this long ago, and the Protocol Buffers JSON mapping writes every int64 and uint64 field as a decimal string for exactly this reason.

In Python the integer is exact in memory, so you only change what goes on the wire:

python
import json

asset = {"assetId": 7340196284512039415, "model": "EliteBook 840 G11", "serial": "5CG4182QWX"}

# Python ints have no size limit, so this round-trips exactly...
print(json.loads(json.dumps(asset))["assetId"])  # 7340196284512039415

# ...but a browser on the other end will round it. Send the ID as a string.
wire = {**asset, "assetId": str(asset["assetId"])}
print(json.dumps(wire))
# {"assetId": "7340196284512039415", "model": "EliteBook 840 G11", "serial": "5CG4182QWX"}

In Go, the ,string option on the struct tag does the same in both directions, so the struct keeps a real int64 while the JSON carries a string:

go
package main

import (
	"encoding/json"
	"fmt"
)

type Asset struct {
	AssetID int64  `json:"assetId,string"`
	Model   string `json:"model"`
}

func main() {
	out, _ := json.Marshal(Asset{AssetID: 7340196284512039415, Model: "ThinkPad X1 Carbon Gen 12"})
	fmt.Println(string(out)) // {"assetId":"7340196284512039415","model":"ThinkPad X1 Carbon Gen 12"}

	var back Asset
	_ = json.Unmarshal(out, &back)
	fmt.Println(back.AssetID) // 7340196284512039415
}

On the client, type the field as string in TypeScript and keep it that way. Compare IDs as strings, use them as Map keys as strings, put them in URLs as strings. If you ever need to sort by ID numerically, convert to BigInt just for the comparison.

Changing an existing API? Add a new field such as assetIdStr next to the numeric one, move clients over, then retire the number. Switching the type of a field in place breaks every client that does id + 1 or id === 42.

Fix 2: read the original digits with the reviver's context.source

Sometimes you do not own the API. A vendor sends "orderId": 7340196284512039415 as a bare number and that is that. For years the only answer was a third-party parser. Now JSON.parse passes a third argument to the reviver: a context object whose source property holds the exact text of the value, before it was turned into a float. Combine that with BigInt and you get the real value back:

js
const body = '{"orderId": 7340196284512039415, "sku": "DELL-LAT-7450", "qty": 2}';

function bigIntReviver(key, value, context) {
  if (
    typeof value === 'number' &&
    !Number.isSafeInteger(value) &&
    context && /^-?\d+$/.test(context.source)
  ) {
    return BigInt(context.source);
  }
  return value;
}

const order = JSON.parse(body, bigIntReviver);
console.log(order.orderId);         // 7340196284512039415n
console.log(typeof order.orderId);  // bigint
console.log(typeof order.qty);      // number

A few details in that reviver matter. It only touches numbers that are not safe integers, so qty stays a normal number and the rest of your code does not have to deal with BigInt everywhere. The regex check skips values like 1e21, which are numbers but not integers written out in full, because BigInt("1e21") throws. And context only exists for primitive values; for objects and arrays it has no source, which the check also handles.

One catch with fetch: res.json() takes no reviver. Read the body as text and parse it yourself. This script runs a tiny stand-in API and reads from it:

js
import http from 'node:http';

// A stand-in for the asset API: one laptop with a 19-digit ID.
const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'application/json');
  res.end('{"assetId":7340196284512039415,"model":"Latitude 7450","unitPrice":1499.90}');
});
await new Promise(r => server.listen(8787, r));

function bigIntReviver(key, value, context) {
  if (typeof value === 'number' && !Number.isSafeInteger(value) &&
      context && /^-?\d+$/.test(context.source)) {
    return BigInt(context.source);
  }
  return value;
}

const res = await fetch('http://localhost:8787/assets/1');
const text = await res.text();          // not res.json(): it takes no reviver
const asset = JSON.parse(text, bigIntReviver);

console.log(asset.assetId);             // 7340196284512039415n
console.log(asset.unitPrice);           // 1499.9

JSON.parse(text, (key, value, context) => {
  if (key === 'unitPrice') console.log(context.source);
  return value;
});
server.close();

The last lines show a second use for context.source. The price arrived as 1499.90; the parsed number is 1499.9. If your invoice screen must show what the supplier sent, the source text is the only place the trailing zero survives.

Fix 3: write big numbers back with JSON.rawJSON

Reading is half the trip. As soon as you try to send that order back, JSON.stringify refuses BigInt values outright. The answer is JSON.rawJSON, which wraps a piece of JSON text so that stringify writes it out unchanged:

js
const order = { orderId: 7340196284512039415n, customer: 'Northwind IT', seats: 40 };

try {
  JSON.stringify(order);
} catch (err) {
  console.log(err.message);  // Do not know how to serialize a BigInt
}

const json = JSON.stringify(order, (key, value) =>
  typeof value === 'bigint' ? JSON.rawJSON(value.toString()) : value
);
console.log(json);  // {"orderId":7340196284512039415,"customer":"Northwind IT","seats":40}

JSON.rawJSON only accepts text that is a valid JSON primitive, so you cannot use it to sneak an object or a half-written value into the output. Avoid the old trick of patching BigInt.prototype.toJSON: it changes behaviour for every library in the process, and it usually returns a string, which quietly changes the type the server receives.

Which runtimes support it

The reviver context and JSON.rawJSON arrived together. According to MDN's compatibility data they ship in Chrome and Edge 114, Firefox 135, Safari 18.4, Node.js 21 and Deno 1.33. Node 20 has neither, so check before you depend on them in a library. A feature test is short:

js
function hasSourceText() {
  let seen = false;
  JSON.parse('1', (key, value, context) => {
    seen = context !== undefined && context.source === '1';
    return value;
  });
  return seen;
}

console.log(hasSourceText());    // true on Node 21+, Chrome 114+, Firefox 135+, Safari 18.4+
console.log(typeof JSON.rawJSON); // function

If you have to support older runtimes, there are parsers on npm that keep big integers as BigInt or as strings. They are slower than the built-in parser, so use them only for the responses that carry big IDs.

Checking a payload by eye

When a number looks wrong, the first question is whether the server sent it wrong or the client rounded it. Copy the raw response from the Network tab (the Response view, not the Preview view, which is already parsed) and look at it in a tool that does not round. The JSON formatter on this site pretty-prints the body and keeps every number exactly as it was typed, 19-digit IDs and trailing zeros included. The JSON viewer shows an array of assets or orders as a table with the same exact numbers, which makes it easy to spot two rows that only differ in the last digits. For a quick look at any response, you can also parse your JSON online on the home page.

If the raw text has the right digits and your app shows the wrong ones, the bug is in the client. If the raw text is already wrong, look at the server: something there converted the value to a double, often a JavaScript backend or a spreadsheet step in an import job.

Wrapping up

  • JSON.parse turns every number into a double, so any integer above 9,007,199,254,740,991 can come back changed, and two IDs can collide.
  • If you own the API, send IDs as strings. It works in every client and every language, and it is what the Protocol Buffers JSON mapping does for 64-bit fields.
  • If you do not own the API, parse with a reviver that reads context.source and returns a BigInt for unsafe integers. Read the body with res.text(), not res.json().
  • To send big values back as numbers, return JSON.rawJSON(value.toString()) from a stringify replacer.
  • Feature-test before relying on either API: Node 20 and older browsers have neither.

None of this is exotic any more. Asset registers, order systems and log pipelines all produce 64-bit IDs, and the day one of them crosses 253 is the day the wrong laptop shows up on someone's screen.

← All JSON articles Browse all categories →