【发布时间】:2020-08-06 15:41:18
【问题描述】:
我正在使用 openweathermap 来获取返回 JSON 对象的天气数据,如下所示:
blank = {
"coord": {"lon": -92.11, "lat": 46.78},
"weather": [
{"id": 800, "main": "Unknown", "description": "Unknown", "icon": "01d"}
],
"base": "stations",
"main": {
"temp": 0,
"feels_like": 0,
"temp_min": 0,
"temp_max": 0,
"pressure": 0,
"humidity": 0,
},
"visibility": 0,
"wind": {"speed": 0, "deg": 0},
"clouds": {"all": 1},
"dt": 0,
"sys": {"type": 1, "id": 3903, "country": "US", "sunrise": 0, "sunset": 0},
"timezone": 0,
"id": 0,
"name": "Unknown",
"cod": 0,
}
我在返回 ["weather"]["description"] 上的字符串时遇到问题,这将引发类型错误 TypeError: list indices must be integers or slices, not str
方法:
class OpenWeather:
def descrip(self):
return self.data["weather"]["description"]
有人有什么建议吗?
【问题讨论】:
-
self.data["weather"]是什么东西? -
现在,“天气”是一个包含一个元素的列表,即字典。我建议删除方括号,从而使“天气”本身成为字典,除非您需要保持这种方式,在这种情况下,Jan 的答案有效。
标签: python json openweathermap