简体   繁体   中英

JSON.parse() reviver function: How to access to a higher level object

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

Reading this one, I tried the code below to get the full object that is containing the property that I specified.

let aTestStr = '{
  "prop1": "this is prop 1", 
  "prop2": {
    "prop2A": 25, 
    "prop2B": 13, 
    "prop2C": "This is 2-c"
  }
}';
let aTestStr = '{"prop1": "this is prop 1", "prop2": {"prop2A": 25, "prop2B": 13, "prop2C": "This is 2-c"}}';
let 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
    if (key == "prop2B") {
      // the object being revived('this') is an object named 'prop2'
      // add a prop to 'this'
      this.prop2D = 60;
      console.log(this);
    }
});

It would return:

{prop2B: 13, prop2C: 'This is 2-c', prop2D: 60}
  1. I guess it omits the prop2A property because this is detected after the conditional finds prop2B ..? I would appreciate to know why, and how to get access to the full object.

  2. Also if you have some time, can you explain how to get access to the higher level than this ? For example, is there a way to print out prop2 (the name of this ) from the conditional if (key == "prop2B") in reviver function?

For question #1 it's because you don't return anything from your reviver, so the object actually looses its properties that have already been parsed.
Simply add return value at the end of your reviver to have the "full" object.

 let aTestStr = '{"prop1": "this is prop 1", "prop2": {"prop2A": 25, "prop2B": 13, "prop2C": "This is 2-c"}}'; let aTestObj = JSON.parse(aTestStr, function(key, value) { if (key == "prop2B") { this.prop2D = 60; console.log(this); } return value; });

And regarding #2, this isn't possible. JSON.parse() reviver visits the values from leaves to root, so the parent never appeared in the reviver before all its children values have been parsed.
The best here is probably to simply walk back your object after revival.

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