实现说明
演示用的数据放在这几个模块级绑定中: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);