"TypeError: list indices must be integers or slices, not str" with a the JSON file from the OpenWeatherMap API

"TypeError: list indices must be integers or slices, not str" with a the JSON file from the OpenWeatherMap API

我有一个从空气污染 API OpenWeatherMap 抓取的 json 文件的问题。

当我尝试使用 aqi = air_data['list']['main']['aqi'] 浏览数据时,出现以下错误:TypeError:列表索引必须是整数或切片,而不是 str

完整代码为:

import requests

URL = "http://api.openweathermap.org/data/2.5/air_pollution?lat=MY_LATITUDE&lon=MY_LONGITUDE&appid=MY_API_KEY"

air_data = requests.get(URL).json()

aqi = air_data['list']['main']['aqi']

print(aqi, 'AirQualityIndex')

用 pprint 格式化的 air_data 看起来像这样:

{'coord': {'lat': MY_LAT, 'lon': MY_LON},
'list': [{'components': {'co': 223.64,
                      'nh3': 0.28,
                      'no': 0,
                      'no2': 5.91,
                      'o3': 42.92,
                      'pm10': 2.14,
                      'pm2_5': 1.79,
                      'so2': 1.79},
       'dt': 1640822400,
       'main': {'aqi': 1}}]}

不明白为什么会认为'aqi'后面的1是字符串。在我使用天气 API 的其他代码中,它没有任何问题。

而不是:

aqi = air_data['list']['main']['aqi']

使用:

aqi = air_data['list'][0]['main']['aqi']

你没有注意到这里有一个列表。