如何修改Python代码适配OpenWeatherMap API v3.0的JSON结构
OpenWeatherMap API v3.0 JSON解析代码修改方案
问题背景
原有针对OpenWeatherMap API v2.5的解析代码:
def get_weather_from_response(json): return WeatherInfo(json['main']['temp'], json['weather'][0]['description'])
v2.5的JSON结构中,temp位于根级main对象,weather是根级数组。升级到v3.0后,核心天气数据全部嵌套在current对象内,原代码路径不再有效。
用户尝试的错误修改:
def get_weather_from_response(json): return WeatherInfo(json['main']['temp'], json[0]['weather'][0]['description'])
正确修改代码
def get_weather_from_response(json): return WeatherInfo(json['current']['temp'], json['current']['weather'][0]['description'])
修改说明
- v3.0 API返回中,
temp字段从根级main对象转移到了current对象下 weather数组同样嵌套在current对象内部,根节点是JSON对象而非数组,因此不能使用json[0]这种数组索引方式
内容的提问来源于stack exchange,提问作者Aleksei
相关产品推荐
相关产品推荐

