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.
You have to parse the json like this based on your response,
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
.
{'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
. You can't access an element in a list with a str
, that's why you are getting that error.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.