如何调用特定的json数据?

时间:2016-11-24 16:53:52

标签: python json api

我目前正在开发一个涉及从RiotGames API获取数据的项目,并会在这个问题上找到一些帮助,但我似乎无法解决。

代码:

import requests
r = requests.get(url="https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/7250/ranked?season=SEASON2016&api_key=ABC420")
json_data = r.json()
get_summoner_data = (json_data["champions"])
print(get_summoner_data)

这是回复

{"summonerId":7250,"modifyDate":1479970436000,"champions":[{"id":111,"stats":{"totalSessionsPlayed":2,"totalSessionsLost":2,"totalSessionsWon":0,"totalChampionKills":8,"totalDamageDealt":211063,"totalDamageTaken":42772,"mostChampionKillsPerSession":7,"totalMinionKills":318,"totalDoubleKills":1,"totalTripleKills":0,"totalQuadraKills":0,"totalPentaKills":0,"totalUnrealKills":0,"totalDeathsPerSession":15,"totalGoldEarned":21574,"mostSpellsCast":0,"totalTurretsKilled":1,"totalPhysicalDamageDealt":33376,"totalMagicDamageDealt":174433,"totalFirstBlood":0,"totalAssists":11,"maxChampionsKilled":7,"maxNumDeaths":8}},{"id":110,"stats":{"totalSessionsPlayed":3,"totalSessionsLost":3,"totalSessionsWon":0,"totalChampionKills":12,"totalDamageDealt":463303,"totalDamageTaken":49704,"mostChampionKillsPerSession":8,"totalMinionKills":675,"totalDoubleKills":0,"totalTripleKills":0,"totalQuadraKills":0,"totalPentaKills":0,"totalUnrealKills":0,"totalDeathsPerSession":15,"totalGoldEarned":35203,"mostSpellsCast":0,"totalTurretsKilled":2,"totalPhysicalDamageDealt":438295,"totalMagicDamageDealt":22391,"totalFirstBlood":0,"totalAssists":28,"maxChampionsKilled":8,"maxNumDeaths":6}}

因此,响应基本上是不同冠军的球员表现的数据,在这种情况下由他们的身份定义。

但是,让我们说有人正在以id 111播放冠军,现在我希望将所有数据连接到该ID,然后能够打印出某些部分ex:MaxDeaths和MaxGold。

但如果找不到该id的数据,我会收到一条消息,例如"未找到数据"。

正如你在这里看到的那样,有一个冠军id 111的数据,但是如何调用才能获得这些数据呢?

旁注以便更好地理解: 一名球员与另外10名球员进行比赛,每队5名。每个人都在扮演不同的冠军。我想看看玩家是否有任何关于该冠军的经验(所有数据),因此将检查冠军ID是否在摘要中。如果是,我将使用该数据进行某种性能分析。

3 个答案:

答案 0 :(得分:0)

所以有很多解决方案,你可以做这样的事情:

def get_champion_info(data, id):
    champions = [c for c in data if c['id'] == id]
    if len(champions):
         return champions[0]
    return "Data not found"

champion_info = get_champion_info(json_data["champions"], 111)

但是返回不同类型的数据(字符串和字典来自一个函数)并不是一个好的解决方案

答案 1 :(得分:0)

for i in json_data["champions"]:
  if i["id"]=="111":
    print("found")
    print(i["stats"]["maxNumDeaths"])
else:
  print("not found")

答案 2 :(得分:0)

API documentation中,我认为有一种方法可以回答您的问题:

 GET /api/lol/{region}/v1.2/champion/{id} 

所以我想你可以做到:

r = requests.get(url="https://na.api.pvp.net/api/lol/na/v1.3/champion/{id}")

当然,请输入冠军ID和你的api密钥。