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

如何处理JSON解析KeyError?wind_gust为空时填充null值

解决方案

方法1:使用字典get()方法(推荐)

利用字典的get()方法安全获取键值,不存在时返回默认值,同时考虑wind_gust列表长度可能小于date_time的情况:

req = requests.get(api_request_url, params=api_arguments)
data = json.loads(req.text)

rows = []

for station in data["STATION"]:
    observations = station["OBSERVATIONS"]
    date_count = len(observations["date_time"])
    # 获取wind_gust列表,不存在则返回空列表
    wind_gusts = observations.get("wind_gust", [])
    
    for j in range(date_count):
        # 检查索引有效性,无效则设为None
        wind_val = wind_gusts[j] if j < len(wind_gusts) else None
        row = {
            "stationId": station["STID"],
            "wind": wind_val
        }
        rows.append(row)

方法2:完善try-except块

如果更倾向于异常捕获的方式,可以同时处理KeyError(键不存在)和IndexError(索引越界):

req = requests.get(api_request_url, params=api_arguments)
data = json.loads(req.text)

rows = []

for station in data["STATION"]:
    observations = station["OBSERVATIONS"]
    date_count = len(observations["date_time"])
    
    for j in range(date_count):
        row = {
            "stationId": station["STID"]
        }
        try:
            row["wind"] = observations["wind_gust"][j]
        except (KeyError, IndexError):
            row["wind"] = None
        rows.append(row)

说明

  • 两种方案都能实现:当wind_gust字段不存在或对应位置无数据时,将wind填充为Python中的None(对应JSON格式的null)。
  • 修复了原代码的两个问题:try块未闭合、未将处理后的row添加到rows列表。

内容的提问来源于stack exchange,提问作者SPena

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 18:50:17