[英]TypeError: list indices must be integers or slices, not str when parsing lists
This is my code: 这是我的代码:
import requests
import json
res = requests.get("http://transport.opendata.ch/v1/connections?
from=Baldegg_kloster&to=Luzern&fields[]=connections/from/prognosis/departure")
parsed_json = res.json()
print(parsed_json['connections']['from']['prognosis'])
"departure"
However, if I run it i get the following errors: 但是,如果我运行它,则会出现以下错误:
Traceback (most recent call last):
File "/home/pi/Desktop/Matura/v7/v7_test.py", line 10, in <module>
print(parsed_json['connections']['from']['prognosis'])
TypeError: list indices must be integers or slices, not str
I've looked at other similar Questions , but I didn't find a solution I am new to coding, so I have no Idea where the problem could be. 我看过其他类似的Questions,但是我没有找到编码的新方法,所以我不知道问题可能在哪里。
You have to parse the json like this based on your response, 您必须根据您的响应来解析json,
import requests
import json
res = requests.get("http://transport.opendata.ch/v1/connections?\
from=Baldegg_kloster&to=Luzern&fields[]=connections/from/prognosis/departure")
parsed_json = res.json()
for item in parsed_json['connections']:
print(item['from']['prognosis']['departure'])
First lets check the contents of parsed_json
. 首先让我们检查
parsed_json
的内容。
{'connections': [{'from': {'prognosis': {'departure': '2018-08-04T11:24:00+0200'}}}, {'from': {'prognosis': {'departure': '2018-08-04T11:53:00+0200'}}}, {'from': {'prognosis': {'departure': '2018-08-04T12:22:00+0200'}}}, {'from': {'prognosis': {'departure': None}}}]}
If you see the output, the children of connections
is not a str
but a list
. 如果看到输出,则
connections
的子代不是str
而是list
。 You can't access an element in a list with a str
, that's why you are getting that error. 您无法使用
str
访问列表中的元素,这就是为什么会出现该错误的原因。
So change 所以改变
print(parsed_json['connections']['from']['prognosis'])
to 至
print(parsed_json['connections'][0]['from']['prognosis'])
You can change the 0
to the index
of the element you want. 您可以将
0
更改为所需元素的index
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.