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

Python映射赋值时处理API响应缺失Key且不中断后续执行的实现方案

解决方案

核心思路是将重复的字段赋值逻辑抽象为循环,通过统一维护映射关系避免冗余代码,同时单个字段处理失败不会阻断后续字段的赋值流程。

方案1:同名字段批量映射

适用于API响应字段名和输出对象字段名完全一致的场景:

import logging

def map_data(output, response):
    # 所有需要映射的字段统一维护在这个列表,30个字段直接追加即可
    map_fields = ["name", "color", "date"]
    target_obj = output["car"]
    for field in map_fields:
        try:
            target_obj[field] = response[field]
        except KeyError:
            logging.error("Key Missing in api Response: %s", field)
    return output

优势:代码量极少,无重复冗余逻辑,单个字段缺失仅打印对应错误日志,不影响其他字段赋值。

方案2:自定义字段映射

适用于API响应字段名和输出对象字段名不一致的场景:

import logging

def map_data(output, response):
    # 键为API响应的字段名,值为输出对象的对应字段名
    field_map = {
        "name": "name",
        "response_color": "color",
        "production_date": "date"
    }
    target_obj = output["car"]
    for resp_key, output_key in field_map.items():
        try:
            target_obj[output_key] = response[resp_key]
        except KeyError:
            logging.error("Key Missing in api Response: %s", resp_key)
    return output

方案3:带默认值的字段映射

适用于字段缺失时不需要抛出日志,只需要填充默认值的场景:

def map_data(output, response):
    map_fields = ["name", "color", "date"]
    target_obj = output["car"]
    # 自定义缺失字段的默认值,可修改为""、0等符合业务要求的值
    default_value = None
    for field in map_fields:
        target_obj[field] = response.get(field, default_value)
        # 如果需要打印缺失日志可以加以下逻辑
        # if field not in response:
        #     logging.error("Key Missing in api Response: %s", field)
    return output

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:15:05