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

如何递归构建层级JSON树?遍历嵌套JSON的spaces节点并保留层级结构

保留嵌套层级遍历JSON中spaces节点的实现方案

问题描述

给定嵌套JSON结构(如下方org.json示例),需要遍历所有key为spaces的节点并完整保留其层级结构。现有DFS实现仅输出叶子节点,无法维持嵌套关系,需修正实现以得到层级化的spaces结构。

输入JSON示例(org.json)

{
    "organization": {
        "id": "e768cffa-28e0-4b42-90af-f22a99d9aae9",
        "name": "season",
        "site": {
            "id": "bca39280-afbe-43ec-8b75-d1763addd953",
            "name": "season",
            "spaces": [
                {
                    "id": "316b0e41-99e1-4748-88ef-e6d5bb0dbba2",
                    "name": "8F",
                    "isBottom": false,
                    "spaces": [
                        {
                            "id": "36a991c2-35da-42b4-9438-b6469179fa4b",
                            "name": "office",
                            "spaces": [],
                            "isBottom": true
                        },
                        {
                            "id": "39456064-0e1c-4b7c-8868-787f530de48f",
                            "name": "lobby",
                            "spaces": [],
                            "isBottom": true
                        },
                        {
                            "id": "89b8708b-4475-4454-8ec0-3de48d7a9663",
                            "name": "RD",
                            "spaces": [],
                            "isBottom": true
                        }
                    ]
                },
                {
                    "id": "ed9f51ef-b9df-4ab3-9b12-7a89d206b874",
                    "name": "ekopro",
                    "isBottom": true,
                    "spaces": []
                }
            ]
        }
    }
}

现有代码问题

现有代码的核心缺陷:

  1. 仅在spaces为空的叶子节点时才将节点加入结果,完全忽略了非叶子节点的层级构建
  2. path的传递逻辑错误,没有将子节点的结果关联到父节点的spaces数组中,导致层级关系断裂

修正后的实现代码

import json

def extract_spaces(obj):
    # 创建当前节点的基础结构
    current_node = {
        "id": obj["id"],
        "spaces": []
    }
    # 递归处理子spaces,填充到当前节点的spaces数组
    for space in obj.get("spaces", []):
        current_node["spaces"].append(extract_spaces(space))
    return current_node

def tree_path(json_data):
    result = []
    # 遍历顶层结构,找到所有根spaces节点
    def traverse(obj):
        if isinstance(obj, dict):
            if "spaces" in obj:
                for space in obj["spaces"]:
                    result.append(extract_spaces(space))
            else:
                for v in obj.values():
                    traverse(v)
        elif isinstance(obj, list):
            for item in obj:
                traverse(item)
    traverse(json_data)
    return result

# 读取JSON文件并处理
with open('org.json') as file:
    data = json.load(file)

# 格式化输出结果
print(json.dumps(tree_path(data), indent=2))

代码说明

  1. extract_spaces函数:递归处理单个space节点,生成包含id和spaces的结构,并将子节点的递归结果填充到当前节点的spaces数组,完整保留层级关系。
  2. tree_path函数:遍历整个JSON结构,定位到顶层的spaces数组,对每个顶层space节点调用extract_spaces,收集所有根节点形成最终结果。
  3. 使用json.dumps格式化输出,保证结果的可读性。

预期输出

[
  {
    "id": "316b0e41-99e1-4748-88ef-e6d5bb0dbba2",
    "spaces": [
      {
        "id": "36a991c2-35da-42b4-9438-b6469179fa4b",
        "spaces": []
      },
      {
        "id": "39456064-0e1c-4b7c-8868-787f530de48f",
        "spaces": []
      },
      {
        "id": "89b8708b-4475-4454-8ec0-3de48d7a9663",
        "spaces": []
      }
    ]
  },
  {
    "id": "ed9f51ef-b9df-4ab3-9b12-7a89d206b874",
    "spaces": []
  }
]

内容的提问来源于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.18 01:07:05