Search code examples
jsonchildren

json inner objects without an array


I've looked for a solution but keep coming up short. I have the following json:

{
   "objects" : 
   {
      "a" : 
      {
         "a1" : { "value1" : "1" }
         "a2" : { "value2" : "2" }
      }, 
      "b" :
      {
         "b1" : { "value1" : "1" }
         "b2" : { "value2" : "2" }
      }
   }
}

So (assuming this is represented in the var jsonObject) if I know all of the object names, getting the value1 from a1 would be:

jsonObject.objects.a.a1.value1

The problem I'm running into is that I don't know the names of the inner objects. It could be

{
   "objects" : 
   {
      "ax7634" : 
      {
         "a1" : { "value1" : "1" }
         "a2" : { "value2" : "2" }
      }, 
      "b78tgf" :
      {
         "b1" : { "value1" : "1" }
         "b2" : { "value2" : "2" }
      }
   }
}

I would say that this is poorly formed JSON data, and that objects should be an array. But I can only play with the hand I'm dealt. So my question is, if I don't know the inner objects name, is there a way to "discover" them or to reference them? Is there a .child(n) method or some such that will give me the nth child?


Solution

  • you need to use a for in loop

    for(var key in objects){
        if (objects.hasOwnProperty(key)){
           objects[key]; // ax7364 in first iteration
        }
    }