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
相关产品推荐
相关产品推荐

