【问题标题】:How to avoid these errors while fetching api in python在python中获取api时如何避免这些错误
【发布时间】:2021-07-02 02:30:22
【问题描述】:
import requests
import json
response = requests.get('http://dataservice.accuweather.com/currentconditions/v1/2807435?apikey=secret')
print(response)
x = response.json()
y = json.dumps(x)
z = json.loads(y)
a = z['WeatherText']
print(a)
yt = input("Press Enter to close")

此代码用于从 accuweather 检索天气数据。当我运行文件时,我得到一个错误:

TypeError: 列表索引必须是整数或切片,而不是 str

初始 json 文件的示例图像是: This image is the output

请帮我解决错误

【问题讨论】:

  • 请使用完整的错误回溯更新您的问题。
  • 顺便说一句,我想你只需要xyz 只是在复制您在 x 中已有的内容。
  • 貌似zdicts的列表,不能用字符串索引列表,必须先提取dict

标签: python api


【解决方案1】:

变量zdictlist。因此,您需要通过以下方式到达第一个位置:

a = z[0]['WeatherText']

【讨论】:

    【解决方案2】:

    你只需要x,但你还需要识别它是一个列表:

    a = x[0]['WeatherText']
    

    【讨论】:

      猜你喜欢
      • 2019-05-03
      • 1970-01-01
      • 2016-08-31
      • 2020-06-03
      • 1970-01-01
      • 2020-01-17
      • 2013-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多