简体   繁体   English

JSON.parse() reviver 函数:如何访问更高级别的对象

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

JSON.parse Reviver function: Access to object being revived? JSON.parse Reviver 函数:访问正在恢复的对象?

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 ..?我猜它省略了prop2A属性,因为this是在条件找到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 ?另外,如果您有时间,您能解释一下如何访问比this更高的级别吗? For example, is there a way to print out prop2 (the name of this ) from the conditional if (key == "prop2B") in reviver function?例如,有没有办法从 reviver 函数的条件if (key == "prop2B")中打印出prop2this的名称)?

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.对于问题 #1,这是因为你没有从你的 reviver 中返回任何东西,所以这个对象实际上失去了它已经被解析的属性。
Simply add return value at the end of your reviver to have the "full" object.只需在 reviver 末尾添加return value即可获得“完整”对象。

 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.关于#2,这是不可能的。 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. JSON.parse() reviver 访问从叶子到根的值,因此在解析所有子值之前,父级从未出现在 reviver 中。
The best here is probably to simply walk back your object after revival.这里最好的可能是在复兴后简单地走回你的对象。

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

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