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

求助:如何使用D3.js将嵌套JSON数据转换为表格?

没问题,我来帮你用D3.js把这份JSON数据转换成你想要的表格。下面是完整的实现方案,包含可直接运行的代码和关键步骤的解释:

完整实现代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>D3.js JSON转表格</title>
    <script src="https://d3js.org/d3.v7.min.js"></script>
    <style>
        table { border-collapse: collapse; margin: 20px; font-family: Arial, sans-serif; }
        th, td { border: 1px solid #ddd; padding: 10px; text-align: left; }
        th { background-color: #f5f5f5; font-weight: bold; }
    </style>
</head>
<body>
    <div id="table-container"></div>

    <script>
        // 模拟你的JSON数据(实际使用时可以替换成你的数据源)
        const jsonData = { 
            "items": [ 
                { 
                    "tableName": "incidents", 
                    "count": 20000, 
                    "columnNames": [ "id", "subject", "category" ], 
                    "rows": [ 
                        [ "61", "Test", null ], 
                        [ "65", "TEST 2", null ]
                    ] 
                } 
            ] 
        };

        // 提取表格核心数据(如果有多个表格,可循环处理items数组)
        const targetTable = jsonData.items[0];
        const headerColumns = targetTable.columnNames;
        const tableRows = targetTable.rows;

        // 创建表格元素并挂载到容器
        const table = d3.select("#table-container")
            .append("table");

        // 生成表头
        const thead = table.append("thead");
        thead.append("tr")
            .selectAll("th")
            .data(headerColumns)
            .enter()
            .append("th")
            .text(col => col.charAt(0).toUpperCase() + col.slice(1)); // 把表头首字母大写,匹配你要的格式

        // 生成表体内容
        const tbody = table.append("tbody");
        const rows = tbody.selectAll("tr")
            .data(tableRows)
            .enter()
            .append("tr");

        // 生成单元格,同时处理null值显示
        rows.selectAll("td")
            .data(row => row)
            .enter()
            .append("td")
            .text(cellValue => cellValue === null ? "Null" : cellValue);
    </script>
</body>
</html>

关键细节说明

  • 数据绑定逻辑:D3的核心是数据驱动DOM,这里用selectAll()+data()+enter()的组合,自动根据数据长度生成对应的表头单元格和表行,不用手动循环创建元素。
  • 表头格式处理:通过charAt(0).toUpperCase() + col.slice(1)把原始的小写表头(id、subject)转换成首字母大写的格式(Id、Subject),完全匹配你期望的输出。
  • Null值处理:专门判断了单元格值为null的情况,把它转换成字符串"Null"显示,避免表格出现空白单元格。
  • 样式优化:加了基础的表格样式,让表格看起来更规整,你可以根据需求调整CSS。

扩展:加载外部JSON数据

如果你的JSON数据是从API接口或者本地文件获取的,把数据替换成d3.json()异步加载即可:

d3.json("你的数据文件路径或API地址")
  .then(jsonData => {
      // 上面的表格生成逻辑放在这里
      const targetTable = jsonData.items[0];
      // ... 后续代码不变
  })
  .catch(error => console.error("数据加载失败:", error));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:28:22