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

如何将Pandas表格数据转换为递归JSON层级树?

如何将树形结构的表格数据转换为嵌套JSON格式?

我们有如下表格数据,其中child_id为0的是根节点(color),其他节点通过child_id关联父节点的id,需要将其转换为带有嵌套children结构的JSON格式。

原始数据

import pandas as pd

data = {
    'id': ['2', '13', '14', '15'],
    'name': ['color', 'red', 'blue', 'ruby red'],
    'child_id': ['0', '2', '2', '13']
}

df = pd.DataFrame(data)

预期输出

[
    {
        "name": "color",
        "id": 2,
        "child_id": 0,
        "children": [
            {
                "name": "red",
                "id": 13,
                "child_id": 2,
                "children": [
                    {
                        "name": "ruby red",
                        "id": 15,
                        "child_id": 13
                    }
                ]
            },
            {
                "name": "blue",
                "id": 14,
                "child_id": 2
            }
        ]
    }
]

实现方案

可以通过构建节点映射表的方式快速组装树形结构,再转换为JSON:

import pandas as pd
import json

# 初始化数据并转换字段类型
data = {
    'id': ['2', '13', '14', '15'],
    'name': ['color', 'red', 'blue', 'ruby red'],
    'child_id': ['0', '2', '2', '13']
}
df = pd.DataFrame(data)
df['id'] = df['id'].astype(int)
df['child_id'] = df['child_id'].astype(int)

# 将数据转为字典列表
records = df.to_dict('records')

# 建立id到节点的映射,同时初始化children列表
node_map = {}
for record in records:
    node = record.copy()
    node['children'] = []
    node_map[node['id']] = node

# 构建树形结构
tree = []
for node in node_map.values():
    parent_id = node['child_id']
    if parent_id == 0:
        tree.append(node)
    else:
        if parent_id in node_map:
            node_map[parent_id]['children'].append(node)

# 转换为格式化的JSON
json_result = json.dumps(tree, indent=2)
print(json_result)

步骤说明

  1. 类型转换:将id和child_id从字符串转为整数,避免匹配时的类型问题。
  2. 节点映射:创建一个以id为键的字典,每个节点提前初始化children空列表,方便后续添加子节点。
  3. 组装树形:遍历所有节点,根节点(child_id=0)直接加入顶层列表;子节点则找到对应父节点,添加到父节点的children中。
  4. 生成JSON:用json.dumps将树形结构转为格式化的JSON字符串。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 07:40:33