The JavaScript exception "BigInt value can't be serialized in JSON" occurs when a BigInt
is encountered in JSON.stringify
with no custom serialization method provided.
TypeError: Do not know how to serialize a BigInt (V8-based) TypeError: BigInt value can't be serialized in JSON (Firefox) TypeError: JSON.stringify cannot serialize BigInt. (Safari)Error type What went wrong?
You are trying to serialize a BigInt value using JSON.stringify
, which does not support BigInt values by default.Sometimes, JSON stringification happens implicitly in libraries, as part of data serialization. For example, sending data to the server, storing it in external storage, or transferring it between threads would all require serialization, which is often done using JSON.
There are several ways to handle this:
JSON.stringify
that converts BigInt values to strings or numbers.BigInt.prototype.toJSON
method globally that gets called whenever a BigInt value is stringified.For more information on various tradeoffs, see BigInt reference.
Examples Providing a custom serialization methodBy default, BigInt values are not serializable in JSON:
const data = { a: 1n };
JSON.stringify(data);
// TypeError: BigInt value can't be serialized in JSON
Assuming you intend for the JSON to contain a number value, here are a few approaches that work:
Convert the BigInt to a number before stringifying:
const data = { a: 1n };
JSON.stringify({ ...data, a: Number(data.a) });
// '{"a":1}'
Provide a replacer function that converts BigInt values to numbers or raw JSON objects:
const data = { a: 1n };
JSON.stringify(data, (key, value) =>
typeof value === "bigint" ? Number(value) : value,
);
// '{"a":1}'
const data = { a: 1n };
JSON.stringify(data, (key, value) =>
typeof value === "bigint" ? JSON.rawJSON(value.toString()) : value,
);
// '{"a":1}'
Provide a BigInt.prototype.toJSON
method that gets called whenever a BigInt value is stringified:
BigInt.prototype.toJSON = function () {
return Number(this);
};
const data = { a: 1n };
JSON.stringify(data);
// '{"a":1}'
BigInt.prototype.toJSON = function () {
return JSON.rawJSON(this.toString());
};
const data = { a: 1n };
JSON.stringify(data);
// '{"a":1}'
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4