← 中文资源

简体中文版本

rawJSON 保留精确数字文本

JSON.rawJSON 把原始数字文本原样写进 JSON:超过安全整数的 ID 和末尾的 1.00 不再被舍入或规范化,解析时还能用 reviver 的 source 取回原文。

阅读英文原文

运行结果

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

rawJSON    : {"id":9007199254740993,"balance":0.1}
plain value: {"id":9007199254740992,"balance":0.1}
round trip : 9007199254740993 string
zeros kept  : [1.0,1.00]

实现说明

顶层就这几处状态: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')]));