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

如何使用Python将递归表结构DataFrame转换为嵌套JSON

递归DataFrame转嵌套JSON实现方案

核心处理逻辑如下:

  • 先建立id到节点对象的映射,实现O(1)复杂度查找父节点
  • 为所有节点预先初始化空的relations子节点列表
  • 遍历所有节点,根据relations字段(存储的父节点id)将当前节点加入对应父节点的子列表中
  • 最终筛选出父节点id为0的根节点,即可得到所需嵌套结构

完整可运行代码:

import pandas as pd
import json

# 构造示例DataFrame,实际使用时替换为你自己的数据读取逻辑(比如pd.read_csv/ pd.read_excel)
df = pd.DataFrame({
    'id': [1, 2, 3, 4, 5, 6, 7],
    'name': ['config', 'buttons', 'accept', 'delete', 'descripton', 'title', 'juan'],
    'relations': [0, 1, 2, 2, 1, 1, 0]
})

# 1. 构建id到节点的映射字典
node_map = {}
for _, row in df.iterrows():
    # 按示例要求id转字符串,不需要可删掉str()
    node_id = str(row['id'])
    node_map[node_id] = {
        "id": node_id,
        "name": row["name"],
        "relations": []
    }

# 2. 填充父子关系
root_list = []
for _, row in df.iterrows():
    current_id = str(row["id"])
    parent_id = str(row["relations"])
    current_node = node_map[current_id]
    if parent_id == "0":
        root_list.append(current_node)
    else:
        # 父节点存在时将当前节点加入父节点的子列表
        if parent_id in node_map:
            node_map[parent_id]["relations"].append(current_node)

# 输出格式化JSON
print(json.dumps(root_list, ensure_ascii=False, indent=2))

补充说明

  • 如果数据量较大(超过10万行),可以将iterrows替换为itertuples提升遍历效率
  • 代码默认所有非0的父id都在当前id列表中,如有异常脏数据可自行添加异常处理分支
  • ensure_ascii=False参数用于兼容中文名称的场景,避免输出Unicode转义字符

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:57:05