实现说明
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));