JSON.parse reviver function has n+1 keys?

六月ゝ 毕业季﹏ 提交于 2019-12-13 01:35:10

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/14294714/json-parse-reviver-function-has-n1-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!