如何迭代嵌套的json dicts?

时间:2016-06-18 19:50:24

标签: python json

我一直在试图弄清楚如何迭代json之类的对象,所以我可以通过它的名字获得用户ID。

JSON

{
    "ApiSearchResult": [
        {
            "totalNumberResults": 55,
            "type": "User",
            "searchResults": [
                {
                    "firstName": "shashank",
                    "name": "0o_shashank._o0",
                    "uid": 81097836
                },
                {
                    "firstName": "Shahnawaz",
                    "name": "0shahnawaz.0",
                    "uid": 83697589
                },
                {
                    "firstName": "Ashu",
                    "name": "ashu.-3",
                    "uid": 83646061
                },
                {
                    "bgImage": "photoalbum_491396460_user82597906-1-jpeg.jpg",
                    "firstName": "Garfield",
                    "name": "beast.boy",
                    "uid": 82597906
                },
                {
                    "firstName": "Bharath",
                    "name": "bharath_mohan69",
                    "uid": 80197615
                },
                {
                    "bgImage": "photoalbum_481041410_user79819261-1-jpg.jpg",
                    "firstName": "Wille-ICE",
                    "name": "blowhole",
                    "uid": 79819261
                }
           ]
       }
    ]
 }

的Python

def getidbyname(name):
    event = response['ApiSearchResult'][0]['searchResults'][0]
    for key, value in event.iteritems():
        if value == name: continue
        elif key == "uid":
            return value

但是,这不起作用,我从未真正使用过这么多嵌套元素。

2 个答案:

答案 0 :(得分:2)

This might work if your response is already a python dictionary:

def getidbyname(name):
    for event in data["ApiSearchResult"][0]["searchResults"]:
        if event["name"] == name:
            return event["uid"]

If your input is a text value, you need to use json.loads(response) to get a python dictionary out of it.

答案 1 :(得分:2)

def getidbyname(name): 
    for i in data['ApiSearchResult'][0]['searchResults']:
        if i['name'] == name:
            return i['uid']