如何在Python中通过值获取动态嵌套JSON结构的索引
Python实现动态嵌套JSON中指定值的索引查找
这问题我熟,动态嵌套的JSON查找目标值的层级索引,用递归就能轻松解决,咱们一步步来实现:
核心思路
因为JSON的嵌套深度是动态未知的,递归遍历是最直接的方案:
- 从根节点开始,每一层遍历
child数组里的元素,记录当前走过的索引路径 - 每访问一个节点,先检查它的
b字段值是不是咱们要找的目标(比如'coconut'或'lemon'),如果是就返回当前的路径 - 如果不是目标节点,就继续递归遍历它的
child数组,把当前索引加到路径里往下传递,找不到就回溯路径继续找同级节点
单目标查找代码实现
这个版本会返回第一个匹配到的目标值的索引路径:
def find_target_index(data, target_values, current_path=None): # 初始化当前路径,首次调用为空列表 if current_path is None: current_path = [] # 检查当前节点的b值是否匹配目标 if data.get('b') in target_values: return current_path.copy() # 遍历子节点递归查找 for idx, child in enumerate(data.get('child', [])): current_path.append(idx) result = find_target_index(child, target_values, current_path) if result is not None: return result # 回溯:移除当前索引,继续遍历同级其他节点 current_path.pop() # 当前分支没找到目标,返回None return None # 测试用的JSON数据 body = { 'a': 1, 'b': 'apple', 'child': [ { 'a': 12, 'b': 'banana', 'child': [ { 'a': 121, 'b': 'mango', 'child': [ { 'a': 1211, 'b': 'coconut', 'child': [] } ] }, { 'a': 122, 'b': 'papaya', 'child': [ { 'a': 1221, 'b': 'lemon', 'child': [] } ] } ] }, { 'a': 13, 'b': 'orenge', 'child': [] } ] } # 测试查找 print(find_target_index(body, ['coconut'])) # 输出: [0, 0, 0] print(find_target_index(body, ['lemon'])) # 输出: [0, 1, 0]
多目标全匹配查找代码
如果需要一次性找到所有匹配目标值的索引路径,可以用这个版本,会返回所有符合条件的路径列表:
def find_all_target_indices(data, target_values, current_path=None, results=None): # 初始化路径和结果列表 if current_path is None: current_path = [] if results is None: results = [] # 匹配到目标就把当前路径加入结果 if data.get('b') in target_values: results.append(current_path.copy()) # 递归遍历所有子节点 for idx, child in enumerate(data.get('child', [])): current_path.append(idx) find_all_target_indices(child, target_values, current_path, results) current_path.pop() return results # 测试查找所有目标 print(find_all_target_indices(body, ['coconut', 'lemon'])) # 输出: [[0, 0, 0], [0, 1, 0]]
代码关键点说明
- 使用
data.get('child', [])避免节点没有child字段时抛出异常 - 每次返回路径时用
current_path.copy(),防止后续回溯修改已经找到的结果 - 回溯操作
current_path.pop()是递归遍历的关键,确保遍历完一个子节点后,路径能回到父节点的状态,继续遍历其他同级子节点
内容的提问来源于stack exchange,提问作者Horizon Tree
相关产品推荐
相关产品推荐

