Code Logo

Custom Deserialize with JSON Reviver

Published at25 Jul 2026
JavaScript String Handling Hard 0 views
Like0

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

Example 1
Input
{}
Output
{}
Explanation

Empty object unchanged

Example 2
Input
{"a":5,"b":3}
Output
{"a":10,"b":6}
Explanation

All numbers doubled

Example 3
Input
{"a":{"b":4}}
Output
{"a":{"b":8}}
Explanation

Nested numbers also doubled

Example 4
Input
{"x":0}
Output
{"x":0}
Explanation

0 doubled is 0

Example 5
Input
{"name":"test","val":10}
Output
{"name":"test","val":20}
Explanation

Strings unchanged, numbers doubled

Algorithm Flow

Recommendation Algorithm Flow for Custom Deserialize with JSON Reviver
Recommendation Algorithm Flow for Custom Deserialize with JSON Reviver

Solution Approach

function solution(jsonStr) {
  return JSON.parse(jsonStr, function(key, value) {
    if (typeof value === 'number') return value * 2;
    return value;
  });
}

Best Answers

javascript - Approach 1
function solution(jsonStr) {
  return JSON.parse(jsonStr, function(key, value) {
    if (typeof value === 'number') return value * 2;
    return value;
  });
}