簡體   English   中英

JSON.parse() reviver 函數:如何訪問更高級別的對象

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

JSON.parse Reviver 函數:訪問正在恢復的對象?

閱讀這篇文章后,我嘗試了下面的代碼來獲取包含我指定的屬性的完整對象。

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);
    }
});

它會返回:

{prop2B: 13, prop2C: 'This is 2-c', prop2D: 60}
  1. 我猜它省略了prop2A屬性,因為this是在條件找到prop2B之后檢測到的 ..? 我很想知道為什么,以及如何訪問完整的對象。

  2. 另外,如果您有時間,您能解釋一下如何訪問比this更高的級別嗎? 例如,有沒有辦法從 reviver 函數的條件if (key == "prop2B")中打印出prop2this的名稱)?

對於問題 #1,這是因為你沒有從你的 reviver 中返回任何東西,所以這個對象實際上失去了它已經被解析的屬性。
只需在 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; });

關於#2,這是不可能的。 JSON.parse() reviver 訪問從葉子到根的值,因此在解析所有子值之前,父級從未出現在 reviver 中。
這里最好的可能是在復興后簡單地走回你的對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM