Python如何查找JSON中未知位置的指定键值并获取对应访问路径
嵌套JSON目标值查询并返回访问路径方案
针对当前JSON结构的轻量实现
你当前使用的JSON结构固定为「顶层字典→值为列表→列表元素为带name/drops字段的字典」,可以直接修改现有生成器逻辑,同步返回路径:
import json # 加载JSON文件 with open("k.json", "r", encoding="utf-8") as f: json_data = json.load(f) # 同步查询drops值和访问路径 query_result = next( ( { "drops": item["drops"], "access_path": f'["{top_key}"][{item_idx}]["drops"]' } for top_key, list_val in json_data.items() for item_idx, item in enumerate(list_val) if item["name"] == "IQasSF" ), {"drops": "not found", "access_path": "not found"} ) # 输出结果 print(f"drops值:{query_result['drops']}") print(f"完整访问路径:{query_result['access_path']}")
运行后返回的访问路径可直接用于Python代码取值,示例输出:
drops值:[0.78, 0.32, 1.28, 0.2, 1.5925, 0.2] 完整访问路径:["Kulla"][1]["drops"]
通用嵌套JSON查询方案
如果后续JSON结构可能发生变化(比如增加嵌套层级、结构不规则),可以用递归遍历方案,适配任意嵌套结构的JSON查询:
import json def search_nested_json(data, target_name, path_prefix=None): if path_prefix is None: path_prefix = [] # 处理字典类型节点 if isinstance(data, dict): # 检查当前节点是否匹配目标条件 if data.get("name") == target_name and "drops" in data: # 格式化完整访问路径 full_path = "".join( f'[{repr(p)}]' if isinstance(p, str) else f'[{p}]' for p in path_prefix + ["drops"] ) return data["drops"], full_path # 递归遍历子节点 for k, v in data.items(): res = search_nested_json(v, target_name, path_prefix + [k]) if res: return res # 处理列表类型节点 elif isinstance(data, list): for idx, item in enumerate(data): res = search_nested_json(item, target_name, path_prefix + [idx]) if res: return res # 无匹配返回None return None # 调用示例 with open("k.json", "r", encoding="utf-8") as f: json_data = json.load(f) result = search_nested_json(json_data, "IQasSF") if result: drops, access_path = result print(f"drops值:{drops}") print(f"完整访问路径:{access_path}") else: print("未找到匹配节点")
内容的提问来源于stack exchange,提问作者IronHeart
相关产品推荐
相关产品推荐

