Python如何实现通用方法校验嵌套JSON(含数组)中指定key是否存在
解决方法
原有代码存在的问题
- 函数名不一致,定义的函数名为
checkElementsExist,实际调用时使用的是finds - 未处理JSON中的数组(list)类型,导致嵌套数组内的key无法被检索
- 存在语法错误,
//不是Python合法注释符号 - Python3中字符串默认是Unicode格式,直接调用
encode方法会返回bytes类型,和字符串拼接会触发类型报错
通用实现代码
以下函数支持任意嵌套结构的JSON(支持dict、list多层嵌套),可检索所有指定key的路径和对应值:
def find_key_in_json(target_key, json_obj, current_path="", result_list=None): if result_list is None: result_list = [] # 处理字典类型节点 if isinstance(json_obj, dict): for key, value in json_obj.items(): if key == target_key: result_list.append({ "path": f"{current_path}{key}", "value": value }) # 递归遍历子节点 new_path = f"{current_path}{key}." if isinstance(value, dict): find_key_in_json(target_key, value, new_path, result_list) elif isinstance(value, list): for idx, item in enumerate(value): find_key_in_json(target_key, item, f"{new_path}[{idx}].", result_list) # 处理数组类型节点 elif isinstance(json_obj, list): for idx, item in enumerate(json_obj): find_key_in_json(target_key, item, f"{current_path}[{idx}].", result_list) return result_list
需求场景使用示例
针对校验cmevents列表所有元素是否都包含sourceEventType key的需求,使用方式如下:
import json # 替换为你的JSON数据加载逻辑 with open("test.json", "r", encoding="utf-8") as f: json_data = json.load(f) # 检索所有sourceEventType节点 match_result = find_key_in_json("sourceEventType", json_data) # 校验cmevents下的节点完整性 cmevents = json_data.get("payload", {}).get("cmevents", []) cmevent_match_count = len([x for x in match_result if x["path"].startswith("payload.cmevents[")]) if cmevent_match_count == len(cmevents): print("校验通过:所有cmevents元素都包含sourceEventType key") else: print(f"校验失败:共{len(cmevents)}个cmevents元素,仅找到{cmevent_match_count}个sourceEventType key")
内容的提问来源于stack exchange,提问作者kaviya .P
相关产品推荐
相关产品推荐

