Question

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 === "")?

Was it helpful?

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 === ""

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top