← 中文资源

简体中文版本

JSON.parse 恢复器拿到原始文本

ES2025 给 reviver 第三个参数:上下文里带值的原始文本。小数字面量 19.99 可以原样存成字符串避免浮点误差,字符串的原始文本则包含引号。

阅读英文原文

运行结果

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

price type: string value: 19.99
stock untouched: 42 number
string source keeps quotes: [ '"Ada"' ]

实现说明

演示用的数据放在这几个模块级绑定中:catalog、product、quoted。

使用要点

  • 每一步打印都带着自己的标签:price type:、stock untouched:、string source keeps quotes:。

常见问题

除了语言运行时还需要什么准备?

什么都不需要——语言运行时是唯一要求。 跨调用保留的状态放在这些顶层绑定里:catalog、product、quoted。

核心语句

return context.source; // "19.99" verbatim, no binary-float rounding
}
JSON.parse('{"name": "Ada"}', (key, value, context) => {
  if (key === "name") quoted.push(context.source);
  return value;
});

代码示例

// The reviver's third argument (ES2025) exposes the source text of each value.
// Decimal literals like 19.99 lose precision as floats, but context.source
// keeps them exactly as written in the document.
const catalog = '{"sku": "ts-100", "price": 19.99, "stock": 42}';

const product = JSON.parse(catalog, (key, value, context) => {
  if (key === "price" && typeof value === "number" && !Number.isInteger(value)) {
    return context.source; // "19.99" verbatim, no binary-float rounding
  }
  return value;
});

console.log("price type:", typeof product.price, "value:", product.price);
console.log("stock untouched:", product.stock, typeof product.stock);

// Strings come back with their quotes included in the source
const quoted = [];
JSON.parse('{"name": "Ada"}', (key, value, context) => {
  if (key === "name") quoted.push(context.source);
  return value;
});
console.log("string source keeps quotes:", quoted);