CodeMonkey CodeMonkey - 1 year ago 65
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("{ .... }");

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 Source

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



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.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download