【问题标题】:TypeError: list indices must be integers or slices, not str when parsing listsTypeError:列表索引必须是整数或切片,而不是解析列表时的str
【发布时间】:2018-08-04 09:26:53
【问题描述】:

这是我的代码:

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"

但是,如果我运行它,我会收到以下错误:

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

我查看了其他类似的问题,但没有找到解决方案 我是编码新手,所以我不知道问题出在哪里。

【问题讨论】:

  • res.json() 里面是什么?

标签: python arrays list error-handling raspberry-pi


【解决方案1】:

首先让我们检查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}}}]}

如果您看到输出,connections 的子代不是str,而是list。您无法使用str 访问列表中的元素,这就是您收到该错误的原因。

所以改变

print(parsed_json['connections']['from']['prognosis'])

到

print(parsed_json['connections'][0]['from']['prognosis'])

您可以将0 更改为您想要的元素的index。

【讨论】:

    【解决方案2】:

    您必须根据您的响应来解析这样的 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'])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-09
      • 2021-11-28
      • 1970-01-01
      • 1970-01-01
      • 2017-11-08
      相关资源
      最近更新 更多