BigInt in JSON and String Representation
You'll learn how BigInt values behave when converted to strings and why they can't be directly serialized to JSON.
The JSON Problem
When you try to use JSON.stringify() with a BigInt, JavaScript throws an error. JSON doesn't have a native BigInt type—it only supports numbers that fit within the standard Number range. Since BigInt can represent integers far beyond that limit, there's no safe way to automatically convert them to JSON without losing information or causing confusion.
const huge = 123456789012345678901234567890n;
// This throws an error:
// JSON.stringify(huge); // ❌ TypeError: Do not know how to serialize a BigInt
Think of it like trying to fit an enormous elephant into a standard-sized box—it simply won't work without some special handling.
String Conversion with toString()
Fortunately, you can convert BigInt to a string using toString(). This gives you a text representation of the number that preserves all digits:
const huge = 123456789012345678901234567890n;
const str = huge.toString();
console.log(str); // "123456789012345678901234567890"
console.log(typeof str); // "string"
The n suffix disappears in the string representation—you just get the digits. If you need to store BigInt in JSON, you must manually convert it to a string first, then parse it back to BigInt when reading:
const data = { id: 9007199254740993n };
const json = JSON.stringify({ id: data.id.toString() }); // Manual conversion
console.log(json); // {"id":"9007199254740993"}
Key Takeaway: BigInt cannot be directly used with JSON.stringify(), but toString() converts BigInt to a string representation for storage or transmission.