You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 08:18:08