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.
Code
// 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
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.