JSON Parse Reviver Source Text

Read each value's original source text in the reviver so decimal literals like 19.99 survive as exact strings instead of rounded floats.

JavascriptData Integrity

Code

javascriptsnippet
22 lines
// 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);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

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

What this snippet does

Demo state sits in top-level bindings: catalog, product, quoted.

What to watch for

  • No third-party code is loaded at any point while this runs.

Applying it

The output labels every step: price type:, stock untouched:, string source keeps quotes:.

Statements that matter

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;
});

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. Its state lives in module-level bindings: `catalog`, `product`, `quoted`.