我有一個從 Air Pollution API OpenWeatherMap 抓取的 json 檔案的問題。
當我嘗試使用 瀏覽資料時aqi = air_data['list']['main']['aqi'],出現以下錯誤:型別錯誤:串列索引必須是整數或切片,而不是 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 是一個字串。在我使用 Wea??ther API 的其他代碼中,它可以正常作業。
uj5u.com熱心網友回復:
代替:
aqi = air_data['list']['main']['aqi']
利用:
aqi = air_data['list'][0]['main']['aqi']
你沒有注意到這里有一個串列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/397735.html
