简体   繁体   English

JSON.parse reviver函数有n + 1个键吗?

[英]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. 我想测试代码重载,它可以在解析JSON字符串时提供 reviver函数。

So this code: 所以这段代码:

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

yields 10 (ok). 收益10 (好)。

But then I asked myself, 'what is this if (k === "") thing?' 但后来我问自己,'这是什么if (k === "")事情是什么? Lets remove it!: 让我们删除它!:

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

Maybe because 5 is an integer? 也许是因为5是整数? Let's try with parseInt : 让我们试试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: 有2个警报:

  • 5

  • [object Object]

IMHO k and v are for key and value , and indeed there is only one key here. 恕我直言kvkeyvalue ,实际上这里只有一个键。

What is this other alert? 什么其他警报? And why do I have to check if (k === "") ? 为什么我要检查if (k === "")

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. 最终使用空字符串和最高值调用reviver,以允许转换最顶层的值。

v is the object itself in the case of k === "" vk === ""的情况下的对象本身

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM