【发布时间】:2019-11-17 18:24:43
【问题描述】:
我想通过 API 为数组中的每个元素从 .json 格式中提取信息。
我尝试使用下面的代码,但出现错误。
# Get the response from the API endpoint.
response = requests.get("http://api.open-notify.org/astros.json")
data = response.json()
print(data["people"][0:2]["name"])
我希望看到列出的每个名称而不是错误:
TypeError:列表索引必须是整数或切片,而不是列表
我知道 [O:2] 数组中有错误。有人可以帮忙吗?
【问题讨论】:
-
您必须遍历包含键为
name的字典的数组,尝试运行names = [di['name'] for di in data["people"][0:2]],这里names将存储您要获得的names的列表(数组)。 -
你能举个你的json例子吗
标签: python python-3.x api slice