Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON: multi-level array

I need to get an item from the json output however the json contents aren't always consistent.

For example if I wanted get the value for "name" it would be ['result']['attributes'][0]['name'];

But in the event that the json is delivered as the second example it would be ['result']['attributes'][1]['name'];

{"result":{
    "attributes":[
        {"user":"newb","name":"mike"},
        {"state":"california","city":"los angeles"}
    ]
}}

{"result":{
    "attributes":[
        {"state":"california","city":"los angeles"},
        {"user":"newb","name":"mike"}
    ]
}}

How would I get the "name" value if the index of the array it's in is unknown?

like image 244
Mike Mills Avatar asked Jun 07 '26 08:06

Mike Mills


1 Answers

var arr = obj.result.attributes;
for (var i=0; i<arr.length; i++)
    if ("name" in arr[i])
         return arr[i].name;

or, if it's always only the two objects in the array:

 var attrs = obj.result.attributes;
 return attrs["name" in attrs[0] ? 0 : 1].name;

But I would insist on a change in that api, the two objects should be just merged.


EDIT: Sorry, here comes the PHP:

$attrs = json_decode($jsonStr, true)["result"]["attributes"];
return $attrs[ isset($attrs[0]["name"]) ? 0 : 1 ];
like image 173
Bergi Avatar answered Jun 10 '26 02:06

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!