JavaScript JSON.parse Reviver: Transform Decoded Values
Quick answer
A reviver is an optional function that transforms parsed values during traversal, after their descendants have been visited.
How it works
JSON.parse(text, (key, value) => ...) visits child properties before their parent, then calls the reviver on the root with an empty-string key. Returning undefined deletes the current property (or makes the root result undefined); return unchanged values explicitly. Use a named-field policy and validate transformed values. The empty key can also occur in real data; it is not a unique root marker.
const x=JSON.parse('{"qty":"3","label":"box"}',(k,v)=>k==="qty"?Number(v):v); console.log(x.qty,typeof x.qty,x.label);Expected output in Node.js:
3 number boxThe selected field changes type; others are returned intact.
const seen=[]; JSON.parse('{"a":{"b":2}}',(k,v)=>{seen.push(k||"root");return v;}); console.log(seen.join(","));Expected output in Node.js:
b,a,rootTraversal reaches children before parents.
Common mistakes
Forgetting return value on nonmatching keys can delete almost the entire document. A reviver runs after numeric parsing, so it cannot generally recover precision from the rounded Number alone.
Practice
Convert every string-valued qty field to a Number, while preserving all unrelated fields in a known schema.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript JSON.parse Reviver: Transform Decoded Values — Knowledge Check
Apply the taught concept and predict the output.
When does a reviver visit an object relative to its child properties?
What does returning undefined from a reviver for an object property do?
What should a reviver return for an unrelated field that must survive?
What is the exact console output in JavaScript JSON.parse Reviver: Transform Decoded Values example 1?
const x=JSON.parse('{"qty":"3","label":"box"}',(k,v)=>k==="qty"?Number(v):v); console.log(x.qty,typeof x.qty,x.label);What is the exact console output in JavaScript JSON.parse Reviver: Transform Decoded Values example 2?
const seen=[]; JSON.parse('{"a":{"b":2}}',(k,v)=>{seen.push(k||"root");return v;}); console.log(seen.join(","));