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

Python递归获取JSON中spaces节点的层级遍历路径问题

递归DFS提取嵌套JSON中spaces节点的层级路径

问题背景

需要遍历嵌套JSON结构,通过DFS递归获取所有spaces节点的层级路径,期望输出为层级化数组列表,例如:
[['8F', 'office'], ['8F','lobby'], ['8F', 'RD'], ['ekopro']]

原JSON示例

{
  "name": "8F",
  "spaces": [
    {"name": "office"},
    {"name": "lobby"},
    {"name": "RD"}
  ],
  "children": [
    {
      "name": "ekopro",
      "spaces": []
    }
  ]
}

现有错误代码

def get_spaces_paths(data, path=[]):
    paths = []
    if 'spaces' in data:
        paths.append(path)
    if 'children' in data:
        for child in data['children']:
            new_path = path + [child['name']]
            paths.extend(get_spaces_paths(child, new_path))
    return paths

错误输出

[[], ['ekopro']]


问题分析

原代码核心问题:

  1. 未将当前节点的name纳入路径,导致8F下的spaces路径缺失父层级
  2. 未处理spaces子节点的名称拼接,仅将空路径/父路径直接加入结果
  3. 无路径回溯机制,不同分支的路径可能互相污染

修正后的代码

def get_spaces_paths(data, current_path=None):
    if current_path is None:
        current_path = []
    result = []
    
    # 将当前节点名称加入路径(如果存在)
    if 'name' in data:
        current_path.append(data['name'])
    
    # 处理当前节点的spaces
    if 'spaces' in data:
        # 若spaces有子项,拼接当前路径与每个space的名称
        for space in data['spaces']:
            result.append(current_path + [space['name']])
        # 若spaces为空,直接将当前路径作为结果(对应ekopro的情况)
        if not data['spaces']:
            result.append(current_path.copy())
    
    # 递归遍历子节点
    if 'children' in data:
        for child in data['children']:
            result.extend(get_spaces_paths(child, current_path))
    
    # 回溯:移除当前节点名称,避免影响其他分支
    if 'name' in data:
        current_path.pop()
    
    return result

验证结果

用示例JSON测试,输出与期望完全一致:

[['8F', 'office'], ['8F', 'lobby'], ['8F', 'RD'], ['ekopro']]

关键说明

  • 路径回溯:递归进入子节点前添加当前节点名,返回后移除,确保不同分支路径独立
  • spaces处理逻辑:区分spaces有子项和空的情况,分别生成对应路径
  • 避免引用污染:空spaces场景下使用current_path.copy(),防止后续修改影响已加入结果的路径

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:53:11