JSON.stringify Refuses BigInt Values

JSON.stringify throws TypeError on BigInt values, so big ids need string encoding, a toJSON method, or a replacer that converts every bigint at once.

JavascriptData Integrity

Code

javascriptsnippet
19 lines
// JSON has no representation for BigInt, so JSON.stringify throws TypeError
const config = { id: 9007199254740993n, name: 'big-id' };
console.log('beyond safe integers:', config.id > BigInt(Number.MAX_SAFE_INTEGER));
try {
  JSON.stringify(config);
} catch (err) {
  console.log('rejected:', err instanceof TypeError, err.message);
}

// Fix 1: stringify big ids as strings at the boundary
console.log(JSON.stringify({ ...config, id: config.id.toString() }));

// Fix 2: a toJSON method decides the wire format per value
const withToJSON = { id: 42n, toJSON: () => '42-from-toJSON' };
console.log(JSON.stringify(withToJSON));

// Fix 3: a replacer converts every bigint field in one place
console.log(JSON.stringify({ n: 42n, list: [1n, 2n] }, (_key, value) =>
  typeof value === 'bigint' ? value.toString() : value));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

beyond safe integers: true
rejected: true Do not know how to serialize a BigInt
{"id":"9007199254740993","name":"big-id"}
"42-from-toJSON"
{"n":"42","list":["1","2"]}

How it works

The file’s state is a handful of top-level bindings: config, withToJSON.

The top-level object literal pins name as plain values — no derivation, no imports behind them.

Watch out for

  • Ready as-is on a bare install of the language.

Using it

The file announces its steps in the output: beyond safe integers:, rejected:.

Key statements

const withToJSON = { id: 42n, toJSON: () => '42-from-toJSON' };
JSON.stringify(config);

Interactive Tools for This Topic

FAQ

Is anything beyond the standard library required?
Nothing beyond the standard library — the snippet is dependency-free. Its state lives in module-level bindings: `config`, `withToJSON`.