Search code examples
javascriptjsonparsingreviver-function

JSON.parse reviver function has n+1 keys?


I wanted to test the code overload which can provide a reviver function when parsing a JSON string.

So this code:

JSON.parse('{"p": 5}', function(k, v) { if (k === "") return v; return v * 2; }).p;

yields 10 (ok).

But then I asked myself, 'what is this if (k === "") thing?' Lets remove it!:

JSON.parse('{"p": 5}', function(k, v) { return v*2;}).p; //undefined !!

Maybe because 5 is an integer? Let's try with parseInt:

JSON.parse('{"p": 5}', function(k, v) { return parseInt(v)*2;}).p; //undefined !!

Very weird...

So then I wanted to see which keys (although there is only one here) are causing the trouble:

JSON.parse('{"p": 5}', function(k, v) { alert(v)}).p;

There were 2 alerts:

  • 5

  • [object Object]

IMHO k and v are for key and value, and indeed there is only one key here.

What is this other alert? And why do I have to check if (k === "")?


Solution

  • The answer is in the link you provided...

    The reviver is ultimately called with the empty string and the topmost value to permit transformation of the topmost value.

    v is the object itself in the case of k === ""