如何使用Python遍历JSON数据提取deadline_time并解决列表索引报错
报错原因
- 从提供的JSON结构可知,
data['events']是列表类型,列表内的每一项才是包含deadline_time字段的字典对象 - 原代码直接用字符串
'deadline_time'作为列表的索引,不符合Python列表的取值规则,因此触发类型错误
修复代码
你需要先遍历data['events']列表中的所有字典元素,再从单个元素中提取deadline_time字段,修改后可运行的代码如下:
import json from urllib.request import urlopen with urlopen("https://fantasy.premierleague.com/api/bootstrap-static/") as response: source = response.read() data = json.loads(source) for event in data['events']: # 可选:用get方法避免字段不存在时报错,无对应字段时返回默认提示 print(event.get('deadline_time', '未查询到deadline_time字段'))
内容的提问来源于stack exchange,提问作者Moe Ghamdi
相关产品推荐
相关产品推荐

