← 中文资源

简体中文版本

JSON.stringify 拒绝 BigInt 值

JSON 没有能承载 BigInt 的类型,JSON.stringify 遇到即抛 TypeError:大整数可在边界转字符串,或用 toJSON/replacer 统一转换。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

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"]}

实现说明

config、withToJSON 定义在模块顶层,中间不经过函数作用域。 一个对象字面量承载 name——每个值都就地写死。

使用要点

  • 直接运行文件,输出会带上标签,比如 beyond safe integers:、rejected:——输出的每一行都能指回产生它的那次调用。

常见问题

需要标准库之外的东西吗?

除标准库外不引入任何东西——这个示例没有依赖。 状态都挂在模块顶层:config、withToJSON。

核心语句

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

代码示例

// 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));