简体   繁体   English

解析JSON:多级数组

[英]Parsing JSON: multi-level array

I need to get an item from the json output however the json contents aren't always consistent. 我需要从json输出中获取一个项目,但json内容并不总是一致的。

For example if I wanted get the value for "name" it would be ['result']['attributes'][0]['name']; 例如,如果我想获得“name”的值,它将是['result']['attributes'][0]['name'];

But in the event that the json is delivered as the second example it would be ['result']['attributes'][1]['name']; 但是如果json作为第二个例子被传递,它将是['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? 如果它所在的数组的索引未知,我将如何获得“name”值?

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. 但是我会坚持改变那个api,两个对象应该合并。


EDIT: Sorry, here comes the PHP: 编辑:对不起,PHP来了:

$attrs = json_decode($jsonStr, true)["result"]["attributes"];
return $attrs[ isset($attrs[0]["name"]) ? 0 : 1 ];

This will return the index into the attributes array that contains the object with a name attribute of "mike" . 这会将索引返回到attributes数组,该数组包含name属性为"mike"

function extractNameFromJson($json) {
    foreach ($json->result->attributes as $i => $attribute) {
        if (isset($attribute['name']) && $attribute['name'] == 'mike') {
            return $i;
        }
    }
}

$index = extractNameFromJson($json);
echo $json->result->attributes[$index]['user'];

==> newb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM