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

Python中JSON数据类型不确定时,如何批量提取id值?

通用提取JSON中动态类型ID的方法

核心问题是部分节点为数组、部分为单个对象,需统一处理逻辑:

1. 编写统一转换的辅助函数

不管输入是单个实例还是数组,先转换成列表再提取ID:

def get_ids(item):
    # 判断是否为列表类型
    if isinstance(item, list):
        return [x.id for x in item]
    # 单个实例则包装为列表
    return [item.id]

2. 调用函数提取ID

替换原遍历代码,直接调用函数即可:

result1 = get_ids(response.root.multiType_1.multiType_1_1)
result2 = get_ids(response.root.multiType_2.multiType_2_2)

# 合并所有结果
all_ids = result1 + result2

补充:原生Python字典的适配方案

如果response是未转成对象的原生字典,修改函数为:

def get_ids(item):
    if isinstance(item, list):
        return [x["id"] for x in item]
    return [item["id"]]

调用示例:

result1 = get_ids(response["root"]["multiType_1"]["multiType_1_1"])
result2 = get_ids(response["root"]["multiType_2"]["multiType_2_2"])

进阶:批量处理所有multiType节点

若需自动处理所有以multiType_开头的节点,无需逐个指定:

all_ids = []
root_node = response.root  # 原生字典则用 response["root"]

for key in root_node:
    if key.startswith("multiType_"):
        sub_content = root_node[key]
        # 获取子节点的唯一键(如multiType_1_1)
        sub_key = next(iter(sub_content.keys()))
        target_item = sub_content[sub_key]
        all_ids.extend(get_ids(target_item))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 05:15:42