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

Java中如何获取嵌套JSON结构中子节点的父节点路径?

从嵌套JSON中获取子节点到顶层节点的完整路径

核心思路

通过递归遍历JSON结构,遇到目标节点时回溯记录所有父节点的title字段,最终整理出从子节点到顶层节点的完整路径。

示例实现(JavaScript)

function findPathToRoot(json, targetTitle, currentPath = []) {
    // 若当前节点有title,先加入路径
    if (json.title) {
        currentPath.unshift(json.title);
        // 匹配到目标节点,直接返回路径
        if (json.title === targetTitle) {
            return currentPath;
        }
    }

    // 遍历当前节点的所有属性
    for (const key in json) {
        if (key === 'title') continue; // 跳过title属性,避免重复处理
        const value = json[key];
        // 处理数组类型的子节点
        if (Array.isArray(value)) {
            for (const item of value) {
                const result = findPathToRoot(item, targetTitle, [...currentPath]);
                if (result) return result;
            }
        } 
        // 处理对象类型的子节点
        else if (typeof value === 'object' && value !== null) {
            const result = findPathToRoot(value, targetTitle, [...currentPath]);
            if (result) return result;
        }
    }

    // 当前分支未找到目标节点,返回null
    return null;
}

// 测试示例JSON
const sampleJson = {
  "title": "P1-main",
  "A": [
    {
      "title": "P1-A1"
    },
    {
      "title": "P1-B1",
      "B": [
        {
          "title": "P1-2"
        }
      ]
    }
  ]
};

// 获取P1-2的路径
const path = findPathToRoot(sampleJson, "P1-2");
console.log(path.join(" → ")); // 输出:P1-2 → P1-B1 → P1-main

更深层次嵌套的示例

测试JSON

{
  "title": "Top-Level",
  "Level1": [
    {
      "title": "L1-Node1",
      "Level2": [
        {
          "title": "L2-Node1",
          "Level3": [
            {
              "title": "L3-Node1",
              "Level4": [
                {
                  "title": "Target-Node"
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}

执行结果

调用findPathToRoot(deepJson, "Target-Node")会返回路径数组:["Target-Node", "L3-Node1", "L2-Node1", "L1-Node1", "Top-Level"],格式化后为:
Target-Node → L3-Node1 → L2-Node1 → L1-Node1 → Top-Level

注意事项

  • 确保所有节点都包含title属性,否则路径会缺失对应层级的节点信息
  • 如果JSON中存在多个同名title,该方法会返回第一个匹配到的节点路径

内容的提问来源于stack exchange,提问作者SaiLaxman Rampally

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 00:45:05