简体   繁体   English

JSON.parse Reviver函数:是否访问正在恢复的对象?

[英]JSON.parse Reviver function: Access to object being revived?

I want to confirm the behavior I am seeing regarding the this reference, and the ability to modify keys (not just values) in an object using the reviver function. 我想确认关于此引用的行为,以及使用齐磊功能修改对象中的键(而不仅仅是值)的能力。

If I pass my reviver function using function (key,value {...} as opposed to using an arrow function (key, value) => {...}, the this reference seems to refer to the object being revived . This is true for sub-objects in the JSON as well. I am seeing this in node.js 8.x on the server, and in Chrome current on the client. 如果我使用函数 (key,value {...}而不是使用箭头函数(key,value)=> {...}来传递reviver函数,则此引用似乎是指要恢复的对象 。 JSON中的子对象也是如此,我在服务器上的node.js 8.x和客户端上的Chrome当前都看到了这一点。

Understandably, if I pass the function as an arrow function, the calling context is preserved. 可以理解,如果我将该函数作为箭头函数传递,则将保留调用上下文。

I am relying on this to add and delete some keys as I parse the JSON. 我在解析JSON时依靠它来添加和删除一些键。

Can I rely on this behavior? 我可以依靠这种行为吗?

var aTestStr = '{"prop1": "this is prop 1",'
    +'"prop2": {"prop2A": 25, "prop2B": 13, "prop2C": "This is 2-c"}'
                +'}';
var aTestObj = JSON.parse(aTestStr, function(key, value) {
    //at this point, this refers to the object being revived
    //E.g., when key == 'prop1', this is an object with prop1 and prop2
    //when key == prop2B, this is an object with prop2A, prop2B and prop2C
    //So is this code reliable?
    if (key == this.prop2B) {
        //Do something, add a prop to this:
        this.prop2BDif = 100 - this.prop2B;
    }
});

Yes it is documented: JSON.parse documentation in the MDN 是的,它已被记录在文档中: MDN中的JSON.parse文档

If a reviver is specified, the value computed by parsing is transformed before being returned. 如果指定了Reviver,则通过解析计算的值将在返回之前进行转换。 Specifically, the computed value and all its properties (beginning with the most nested properties and proceeding to the original value itself) are individually run through the reviver. 具体而言,计算值及其所有属性(从嵌套最多的属性开始,一直到原始值本身)都通过规则运算器运行。 Then it is called, with the object containing the property being processed as this , and with the property name as a string, and the property value as arguments. 然后调用它,对象包含按此方式处理的属性 ,属性名称为字符串,属性值作为参数。

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

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