CodeMonkey CodeMonkey - 2 months ago 7
JSON Question

Getting value of a nested object in JSON

I want to get the req1 value in the JSON below, programatically.Here RequestTypeItem can be changed as well, so it is not fixed. Else I could have navigated it using object.subobject

I was able to navigate till slots using

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


But I can navigate further programatically.

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

Answer

In your JSON your request does not have a property of intent, it does have a property type, so you then you can access the property you want with

b.request.type.slots.RequestTypeItem.value

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

Edit: After reading your question again, maybe this is what you want:

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

Here I loop through all the properties on slots, checking that the property does indeed belong to slots, and that it has value property.

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