实现说明
顶层就这几处状态:ledger、plain、back。
使用要点
- 跑完文件,输出里会留下标记——
plain value:、round trip :。
常见问题
不安装任何包也能运行吗?
可以,开箱即跑——没有引用任何内建 API 之外的东西。 跨调用保留的状态放在这些顶层绑定里:ledger、plain、back。
核心语句
const back = JSON.parse(JSON.stringify(ledger), (key, value, context) =>
key === 'id' && typeof context?.source === 'string' ? context.source : value,
);
const plain = JSON.stringify({ id: 9007199254740993, balance: 0.1 });
代码示例
// JSON.rawJSON stores the exact digit text instead of a rounded float.
const ledger = {
id: JSON.rawJSON('9007199254740993'),
balance: JSON.rawJSON('0.1'),
};
console.log('rawJSON :', JSON.stringify(ledger));
// A regular number is silently rounded past Number.MAX_SAFE_INTEGER
const plain = JSON.stringify({ id: 9007199254740993, balance: 0.1 });
console.log('plain value:', plain);
// The reviver's third argument carries the original source text
const back = JSON.parse(JSON.stringify(ledger), (key, value, context) =>
key === 'id' && typeof context?.source === 'string' ? context.source : value,
);
console.log('round trip :', back.id, typeof back.id);
// Trailing zeros survive too: 1.0 and 1.00 stay distinct texts
console.log('zeros kept :', JSON.stringify([JSON.rawJSON('1.0'), JSON.rawJSON('1.00')]));