2016-11-09 196 views
-3

我正在玩傳說api的聯盟,無論如何,我做了這個非常簡單的程序。Python,從JSON獲取具體數據

import requests 
region = input("Enter a region ") 
summonerName = input("Enter Summoner Name ") 
apikey = input("Enter APIKey ") 
r = requests.get(url="https://" + region + ".api.pvp.net/api/lol/" + region + "/v1.4/summoner/by-name/" + summonerName + "?api_key=" + apikey) 
print(r.json()) 

這就是它返回的結果。

{'hiimeric': {'revisionDate': 1478543641000, 'name': 'Hi Im Eric', 'id': 36843151, 'profileIconId': 13, 'summonerLevel': 30}} 

所以我的問題是現在,我怎麼可能例如得到它只是後「名」或只「名」和「profileIconId」?謝謝!

+0

您是否假設「hiimeric」的值是已知的或未知的? (到目前爲止的答案假定它是已知的。)你確定只有一個用戶的值將被返回嗎? –

+0

這只是一本字典,包含另一本字典。也許你想[閱讀字典使用教程](https://docs.python.org/3/tutorial/datastructures.html#dictionaries)? –

+1

[訪問python字典的元素]的可能重複(http://stackoverflow.com/questions/5404665/accessing-elements-of-python-dictionary) –

回答

0

JSON對象實際上只是字典和列表的組合。因此,你可以用下面的打印的姓名和profileIconId:

print(r.json()['hiimeric']['name']) 
print(r.json()['hiimeric']['profileIconId']) 
0

JSON對象有兩種:dictlist。在這種情況下,它是dictionary。如果你想明確地知道,使用這樣的函數type

obj = r.json() 
print(type(obj))