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

如何提取JSON树形结构中的所有ID并保存到本地存储?

提取JSON树形结构中所有ID的解决方案

问题描述

有一个嵌套树形结构的JSON文档,部分内容如下:

"childs": [
    {
      "id": "id1",
      "name": "name1",
      "childs": []
    },
    {
      "id": "id2",
      "name": "name21",
      "childs": [
        {
          "id": "id3",
          "name": "name123124",
          "childs": [
            {
              "id": "id4",
              "name": "namewe1231",
              "childs": [
                {
                  "id": "id5",
                  "name": "name123123",
                  "childs": [
                    {
                      "id": "id5"
                      // 后续内容省略
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
]

需要提取所有id字段值,按每行一个的格式保存到本地文件。之前尝试的代码仅能获取第一个id:

string source = File.ReadAllText(jsonModelPath);
dynamic data = JObject.Parse(source);
File.WriteAllText(path, data.id);

解决方案

由于JSON是嵌套树形结构,需要通过递归遍历所有节点及其子节点来收集全部id。以下是基于Newtonsoft.Json的实现代码:

完整实现代码

using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.IO;

class IdExtractor
{
    static void Main(string[] args)
    {
        string jsonInputPath = "你的JSON文件路径";
        string outputFilePath = "输出文件路径";

        // 读取并解析JSON内容
        string jsonContent = File.ReadAllText(jsonInputPath);
        JToken rootToken = JToken.Parse(jsonContent);

        // 初始化列表存储所有id
        List<string> allIds = new List<string>();
        // 递归收集id
        TraverseNodes(rootToken, allIds);

        // 将id写入文件,每行一个
        File.WriteAllLines(outputFilePath, allIds);
    }

    /// <summary>
    /// 递归遍历JSON节点,收集所有id
    /// </summary>
    static void TraverseNodes(JToken currentToken, List<string> idList)
    {
        // 处理对象节点:提取当前id(如果存在)
        if (currentToken is JObject node)
        {
            JToken idValue = node["id"];
            if (idValue != null && idValue.Type == JTokenType.String)
            {
                idList.Add(idValue.ToString());
            }

            // 递归处理子节点数组
            JToken childNodes = node["childs"];
            if (childNodes is JArray childArray)
            {
                foreach (JToken child in childArray)
                {
                    TraverseNodes(child, idList);
                }
            }
        }
        // 处理数组节点:遍历每个元素继续递归
        else if (currentToken is JArray array)
        {
            foreach (JToken item in array)
            {
                TraverseNodes(item, idList);
            }
        }
    }
}

代码说明

  1. 递归遍历逻辑:TraverseNodes方法会检查当前节点类型:
    • 如果是JObject,先判断是否包含id字段,有则加入列表;再检查childs数组,递归处理每个子节点。
    • 如果是JArray,直接遍历数组内的每个元素,继续递归处理。
  2. 写入文件:File.WriteAllLines方法会自动将列表中的每个id单独写入一行,满足格式要求。

内容的提问来源于stack exchange,提问作者Alexey Savelyev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:30:55