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

Python中分类树输出列表转指定JSON/CSV格式的实现方案咨询

实现代码

你原有的路径生成逻辑没问题,直接保留即可,在此基础上增加两种格式的转换逻辑即可,已经内置10列的最大限制,超过部分会自动截断:

import json
import csv
from pprint import pprint

# 原有分类树转路径元组逻辑,新增10列截断处理
def paths(tree):
    tree_name = next(iter(tree.keys()))
    if tree_name == 'children': 
        for child in tree['children']:
            for descendant in paths(child):
                yield (tree['id'],) + descendant[:9]
    else:
        yield (tree['id'],)

# 转换为要求的JSON格式
def to_json(path_list):
    return [
        {f"column{idx+1}": str(val) for idx, val in enumerate(path)}
        for path in path_list
    ]

# 转换为要求的CSV格式,支持自定义输出路径
def to_csv(path_list, output_path="result.csv"):
    max_col = min(max(len(p) for p in path_list), 10)
    headers = [f"column{i+1}" for i in range(max_col)]
    with open(output_path, "w", newline="", encoding="utf-8") as f:
        writer = csv.writer(f)
        writer.writerow(headers)
        for path in path_list:
            row = [str(v) for v in path] + [""] * (max_col - len(path))
            writer.writerow(row[:10])
    return max_col

# 调用示例
if __name__ == "__main__":
    # 替换为你的实际分类树数据
    # tree = xxx
    path_list = list(paths(tree))
    # 输出JSON
    json_result = to_json(path_list)
    pprint(json_result)
    # 保存JSON到文件
    with open("result.json", "w", encoding="utf-8") as f:
        json.dump(json_result, f, indent=4, ensure_ascii=False)
    # 保存CSV到文件
    col_count = to_csv(path_list)
    print(f"CSV生成完成,共{col_count}列")

功能说明

  • 所有id会自动转换为字符串格式,匹配JSON示例要求
  • CSV会自动按最长路径的长度生成表头,路径长度不足的位置自动留空
  • 全局限制最大10列输出,超过10级的路径会自动截断后面的层级
  • 两种转换逻辑和原有路径生成逻辑拆分,你可以按需单独调用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:36:04