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

使用Python将CSV转换为D3.js所需的嵌套JSON格式

把CSV转换为D3.js嵌套层级JSON结构(匹配mbostock的示例格式)

我明白你想要的是那种类似flare.json的嵌套{name: "...", children: []}结构——这种格式是D3.js层级可视化(比如树图、打包图)的标准输入。针对你的CSV数据,我来帮你搞定这个转换,顺便排查可能的报错原因。

首先先明确你的需求:你的CSV是三级层级(L1→L2→L3),最后一级关联SIZE数值,最终要生成非叶子节点带children数组、叶子节点带value(对应SIZE)的嵌套JSON。

先解决CSV格式的坑

你给出的示例CSV用空格分隔,但L2字段是CB Current Acct(带空格),这会导致CSV读取工具错误拆分字段,大概率是你代码报错的原因之一。先把CSV改成逗号分隔的规范格式:

L1,L2,L3,SIZE
CB,CB Current Acct,Tween/Youth,10
CB,CB Current Acct,Students,20

完整Python转换代码

下面是经过验证的代码,能完美生成你需要的嵌套结构:

import csv
import json

def build_d3_hierarchy(csv_path):
    # 构建D3需要的根节点(如果不需要根节点,可以直接返回一级节点列表)
    root = {"name": "Root", "children": []}

    with open(csv_path, mode="r", encoding="utf-8") as csv_file:
        # 用逗号分隔读取CSV,确保带空格的字段被正确识别
        reader = csv.DictReader(csv_file, delimiter=",")
        
        for row in reader:
            # 提取每一行的层级数据和数值,做基本的清洗
            l1 = row["L1"].strip()
            l2 = row["L2"].strip()
            l3 = row["L3"].strip()
            try:
                size = int(row["SIZE"].strip())
            except ValueError:
                # 处理SIZE不是整数的情况,比如设为0或者跳过该行
                print(f"警告:行{row}的SIZE不是有效整数,设为0")
                size = 0

            # 查找或创建一级节点
            l1_node = next((child for child in root["children"] if child["name"] == l1), None)
            if not l1_node:
                l1_node = {"name": l1, "children": []}
                root["children"].append(l1_node)

            # 查找或创建二级节点
            l2_node = next((child for child in l1_node["children"] if child["name"] == l2), None)
            if not l2_node:
                l2_node = {"name": l2, "children": []}
                l1_node["children"].append(l2_node)

            # 创建三级叶子节点(带value,没有children)
            # 先检查是否已存在同名节点,避免重复
            l3_node = next((child for child in l2_node["children"] if child["name"] == l3), None)
            if not l3_node:
                l3_node = {"name": l3, "value": size}
                l2_node["children"].append(l3_node)

    return root

# 执行转换并保存JSON
if __name__ == "__main__":
    hierarchy = build_d3_hierarchy("your_data.csv")
    with open("d3_hierarchy.json", "w", encoding="utf-8") as json_file:
        json.dump(hierarchy, json_file, indent=2, ensure_ascii=False)

代码说明

  1. CSV读取:用csv.DictReader读取,指定逗号分隔,确保带空格的字段被正确解析,避免KeyError。
  2. 层级构建:逐层查找节点,不存在则创建——非叶子节点保留children数组,叶子节点用value存储SIZE数值,完全匹配D3示例的格式。
  3. 异常处理:加入了SIZE字段的类型转换异常处理,避免因数据格式错误导致程序崩溃。
  4. 输出格式:生成的JSON带缩进,可读性强,兼容D3的所有层级可视化示例。

生成的JSON示例

用你的测试数据运行后,会得到如下JSON:

{
  "name": "Root",
  "children": [
    {
      "name": "CB",
      "children": [
        {
          "name": "CB Current Acct",
          "children": [
            {
              "name": "Tween/Youth",
              "value": 10
            },
            {
              "name": "Students",
              "value": 20
            }
          ]
        }
      ]
    }
  ]
}

如果不需要顶层的Root节点,你可以直接返回root["children"],这样输出的就是一级节点的数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 04:08:34