Search code examples
phparraysjsonobjectgetjson

How to access JSON object without knowing its name (and that is not in an array)


My problem is rather simple, at least I hope so, but I just cannot find the solution. I have a JSON string, which I got from a get request to a server.

Exemple of my JSON :

"body":[
{
   "_id":"70:ee:50:05:00:aa",
   "place":{
      "location":[
         2.4358958,
         49.503012
      ],
      "altitude":89,
      "timezone":"Europe/Paris"
   },
   "mark":8,
   "measures":{
      "02:00:00:04:f8:6a":{
         "res":{
            "1431926951":[
               7.9,
               83
            ]
         },
      "type":[
         "temperature",
         "humidity"
         ]
      },
      "70:ee:50:05:00:aa":{
         "res":{
            "1431932787":[
               1009.4
            ]
         },
         "type":[
            "pressure"
         ]
      }
  },
  "modules":[
     "02:00:00:04:f8:6a"
  ]
},

I need to accessthe temperature value, so following this example I would do this : $value = body->measures->02:00:00:04:f8:6a->res->1431926951[0].

I know i can't just do this : measures->02:00:00:04:f8:6a. The cool thing is that this difficulty can be solved doing this : $module = body->modules[0] and then I can use this variable. So it would look like this : body->measures->$module->res->1431926951[0].

What I can't seem to do though is the final step : res->1431926951[0]. This number seem completely random I can't find this value anywhere else in the JSON so I can't use the same trick I did for 02:00:00:04:f8:6a. So my question is how can I access the first value of the array located inside the object "1431926951" without knowing its name ?

Thank you very much for taking the time to help me.

EDIT : here is the code I am using in PHP

$results = json_decode($resp);
foreach($results->body as $result){
    $id = $result->_id;
    $lat = $result->place->location[0];
    $lng = $result->place->location[1];
    $module = $result->modules[0];
    $type = $result->measures->$module->type[0];
    $value = "1431926951";
    //$test = $result->measures->$module->res->$value[0];
    /*$res = $result->measures[$result->measures[0]]->res;
    $test = $res[Object.keys($res)[0]][0];*/
    echo 'Id: '.$id.' - Lat: '.$lat.' - Lng: '.$lng.' - test: '.$test."<br>";
}

Solution

  • You can access with the Object.keys to the name of the property in JavaScript.

    var res = obj.body.measures[ obj.body.modules[0] ].res;
    console.log( res[ Object.keys(res)[0] ][0]); // prints 7.9
    

    See demo

    EDIT (PHP version, only 2 lines):

    With PHP is the same but using key and stdClass (json_decode returns stdClass)

    $res = $obj->body->measures->{ $obj->body->modules[0] }->res;
    echo $res->{ key( (array) $res ) }[0]; // prints 7.9
    

    See demo

    Hope help.