簡體   English   中英

在JSON中獲取嵌套對象的值

[英]Getting value of a nested object in JSON

我想以編程方式在下面的JSON中獲取req1值。這里RequestTypeItem也可以更改,因此它不是固定的。 否則我可以使用object.subobject進行導航

我能使用導航,直到插槽

var b = JSON.parse("{ .... }");
b.request.intent.slots.RequestTypeItem.value

但是我可以通過編程進一步導航。

{"request": {
  "locale": "en-US",
  "timestamp": "2016-09-25T00:36:14Z",
  "type": {
    "name": "request",
    "slots": {
      "RequestTypeItem": {
        "name": "RequestTypeItem",
        "value": "req1"
      }
    }
  }
}
}

在JSON中,您的請求沒有intent屬性,它具有屬性類型 ,因此您可以使用來訪問所需的屬性

b.request.type.slots.RequestTypeItem.value

JSFiddle: https ://jsfiddle.net/9cexbn54/

編輯:再次閱讀您的問題后,也許這是您想要的:

 // loop through all properties on the slots object
for (var i in b.request.type.slots) {
    if (b.request.type.slots.hasOwnProperty(i)) {  // make sure it is a property belonging directly to slots, and not "inherited" from the prototype chain
    if (b.request.type.slots[i].value) { // make sure that the sub-property of slots has a value property
      document.getElementById("output").innerHTML = b.request.type.slots[i].value;
      break; // break out of the loop after getting a value
    }  
  }
}

在這里,我遍歷插槽上的所有屬性,檢查該屬性確實確實屬於插槽,並且具有value屬性。

JSFiddle: https ://jsfiddle.net/9cexbn54/1/

我給了一個鏈接,有些人發現它沒有用。 以下是req1的內容:

在此處輸入圖片說明

 $data=@'
[{"request": {
  "locale": "en-US",
  "timestamp": "2016-09-25T00:36:14Z",
  "type": {
    "name": "request",
    "slots": {
      "RequestTypeItem": {
        "name": "RequestTypeItem",
        "value": "req1"
      }
    }
  }
}
}]
'@
$json=ConvertFrom-Json $data
$json.request.type.slots.RequestTypeItem.value

暫無
暫無

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

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