将json解析为Python并对key进行过滤时出现问题

2024-10-04 03:25:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望有人能给我指出正确的方向。我对Python还比较陌生。我正在使用一个openergastapi,尝试导入/解析一个json文件,并对一些元素进行过滤。我可以毫无问题地打印整个json文件,但是只要我尝试在driverId上进行过滤,它就会失败。我做错什么了?提前感谢:

import json
import requests

response = requests.get("https://ergast.com/api/f1/current/last/results.json?")
data = response.json()
print (data["driverId"])

编辑:我得到的答复是:

Traceback (most recent call last):
  File "python", line 6, in <module>
KeyError: 'driverId'

Tags: 文件httpsimportjson元素datagetresponse
1条回答
网友
1楼 · 发布于 2024-10-04 03:25:42

driverId嵌套在数组中,数组中的Results依次在Races内,数组中的RaceTable依次在MRData内。因此,要获得第一个driveId,您必须使用以下代码

print(data['MRData']['RaceTable']['Races'][0]['Results'][0]['Driver']["driverId"])

如果您想要得到driverId的所有值,那么您将编写一个for循环

for driver in data['MRData']['RaceTable']['Races'][0]['Results']:
    print(driver['Driver']["driverId"])

相关问题 更多 >