简体   繁体   English

如何遍历嵌套的json字典?

[英]How can I iterate over nested json dicts?

I've been trying to figure out how I can iterate over a json like object, so I could get a user id by its name. 我一直在尝试找出如何遍历像json这样的对象,因此可以通过其名称获取用户ID。

json 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

But, this won't work, I've never really worked with this many nested elements. 但是,这行不通,我从未真正使用过这么多嵌套元素。

This might work if your response is already a python dictionary: 如果您的响应已经是python字典,则可能会起作用:

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. 如果您输入的是文本值,则需要使用json.loads(response)从中获取一个python字典。

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

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

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