logo
post image

Using the Reviver Function in JSON.parse

Reviver - The Second Parameter of JSON.parse

Years after working with JSON.parse, I came to know that it also accepts an optional second parameter !

This optional second parameter is the reviver function. The purpose of this function is to modify the result before returning. In simple terms this reviver function can be thought of as a filter function. All parsed values are passed through this reviver function in key-value pair before being returned.

JSON.parse(jsonString, function (key, value) {
 	// all key-value pairs in the JSON object are passed here
	
	// return value for the key
	return value;
});

Important : If a key-value pair passing through this reviver method causes an error or the reviver method returns “undefined” for any pair, then that key-value pair is dropped from the final parsed JSON object.

Example #1

Consider the following code :

var jsonString = '{"1": "A", "2": "B", "3": "D", "4": "C"}';
var parsedJson = JSON.parse(jsonString, function (key, value) {
    if(key === 3)
        return "C";

    if(key === 4)
        return "D";

    return value; 
});

console.log(parsedJson);

The output for the above snippet will be:

{ 1: "A", 2: "B", 3: "C", 4: "D" }

Example #2

var jsonString = '[{"team":"Ferrari","drivers":[{"name":"Vettel"},{"name":"Raikkonen"}]}]';
var parsedJson = JSON.parse(jsonString, function(key, value) {
    if(value === "Ferrari")
        return "Scuderia Ferrari";

    if(value === "Raikkonen")
        return "Leclerc";

    return value; 
});

console.log(parsedJson);

The output :

[{ "team": "Scuderia Ferrari", "drivers": [{"name": "Vettel"}, {"name": "Leclerc"}] }]

Example #3

When the JSON is nested, reviver begins with the most inner properties.

var jsonString = '{"one": 1, "two": 2, "three": {"four": 4, "five": {"six": 6}}}';
var parsedJson = JSON.parse(jsonString, function(key, value) {
    console.log(key); 
    return value; 
});

The output will be :

one
two
four
six
five
three
""

The last key is always a blank " ".