2

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

Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
Royi Namir
  • 144,742
  • 138
  • 468
  • 792

1 Answers1

3

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

Prinzhorn
  • 22,120
  • 7
  • 61
  • 65
  • I guess I should do an eye check. – Royi Namir Jan 12 '13 at 15:24
  • v is the inner object or the outer whole object ? – Royi Namir Jan 12 '13 at 15:26
  • Which inner object? There's an object with a key `p`. Open the console (ctrl+i in Chrome, ctrl+shift+k in Firefox) and paste `JSON.parse('{"p": 5}', function(k, v) { console.log(v); return v; });` – Prinzhorn Jan 12 '13 at 15:32
  • It's the whole thing `{"p": {"a":2}}`. What else should it be? – Prinzhorn Jan 12 '13 at 15:35
  • `JSON.parse('{"p": {"a":2}}', function(k, v) { if (k === "") alert(v.p.a); return v * 2; });` alerts undefined. isn't it suppose to return 2? – Royi Namir Jan 12 '13 at 15:36
  • In case of `k === ""` there's no return statement = undefined. Thus you make the whole thing undefined. – Prinzhorn Jan 12 '13 at 15:37
  • IMHO the return is for the outer assignment. it should alert 2 – Royi Namir Jan 12 '13 at 15:39
  • Forget what I wrote above: the `v * 2` returns `NaN` because `v` contains `{a: 4}`. And the case `k === ""` is the very last, thus `v.p.a` is in fact `NaN.a` which is undefined. – Prinzhorn Jan 12 '13 at 15:39
  • wrote above where ? you wrote many lines...can you edit your answer so it will be clearer also to others :-) ? – Royi Namir Jan 12 '13 at 15:43
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/22638/discussion-between-prinzhorn-and-royi-namir) – Prinzhorn Jan 12 '13 at 15:43