2016-06-18 184 views
1

我一直想弄清楚如何迭代一個像對象的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 

但是,這是不行的,我從來沒有真正有這麼多的嵌套元素的工作。

+0

你使用的是嵌套字典嗎?有用於處理python中的JSON的庫。 https://docs.python.org/2/library/json.html – Thoth19

回答

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

謝謝!我嘗試過,但我在最後加上了[0],因爲我認爲'searchResults'有一個列表。但是這並沒有達到我所需要的,但這是有效的。 – Michael

2

如果你的反應已經是一個Python字典這可能會實現:

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

如果你的輸入是文本值,則需要使用json.loads(response)得到一個Python字典出來。