简体   繁体   中英

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.

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.

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

If a reviver is specified, the value computed by parsing is transformed before being returned. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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