Custom Deserialize with JSON Reviver
Write a JavaScript function that takes a JSON string and uses JSON.parse() with a reviver function that doubles all numeric values during parsing. The reviver callback is called for each key-value pair, allowing transformation of the parsed result.
JSON.parse() accepts an optional reviver parameter: a function that transforms the parsed object before it is returned. The reviver is called for each key-value pair (including nested objects), with the ability to return the value as-is, modify it, or return undefined to delete the property. The reviver runs bottom-up: nested objects are processed before their parents.
The reviver pattern is a JavaScript-specific feature for post-processing JSON data. Common uses include reviving date strings into Date objects, converting serialized number strings back to numbers, sanitizing data, applying default values, and converting snake_case keys to camelCase.
Time complexity is O(n) where n is the number of key-value pairs in the JSON. Space complexity is O(n) for the parsed object tree. The reviver is called once per key-value pair and can modify the result tree.
Edge cases include nested objects (reviver runs on innermost objects first), arrays (reviver is called with index as key and array as the parent), null values, and returning undefined from the reviver to remove a property from the result.
Example Input & Output
Empty object unchanged
All numbers doubled
Nested numbers also doubled
0 doubled is 0
Strings unchanged, numbers doubled
Algorithm Flow

Solution Approach
Best Answers
function solution(jsonStr) {
return JSON.parse(jsonStr, function(key, value) {
if (typeof value === 'number') return value * 2;
return value;
});
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
