2016-09-25 66 views
-1

嵌套對象的值,我想在下面的JSON的REQ1值,programatically.Here RequestTypeItem也可被改變,所以它是不固定的。我還能使用object.subobject獲得在JSON

我能夠導航至插槽使用

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" 
     } 
    } 
    } 
} 
} 

回答

2

在你的JSON你的要求不具有意圖一個屬性,它確實有一個屬性,讓你,那麼你可以用

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

這裏我循環遍歷插槽上的所有屬性,檢查屬性確實屬於插槽,並且它具有值屬性。

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

0

我給了其中一些你發現它不是有用的鏈接。 這裏是會得到REQ1:

enter image description here

[email protected]' 
[{"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