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

如何使用Python将含嵌套dict、list的JSON转换为表格格式

嵌套Dict/List结构JSON转表格Python实现

完整实现代码

import csv

# 原始JSON数据
raw_data = {
    'tables': [
        {
            'name': 'PrimaryResult',
            'columns': [
                {'name': 'TimeGenerated', 'type': 'datetime'},
                {'name': 'OperationName', 'type': 'string'},
                {'name': 'Category', 'type': 'string'}
            ],
            'rows': [
                ['2021-08-24T04:08:01.966Z', 'Restore application', 'ApplicationManagement'],
                ['2021-08-24T06:52:22.14Z', 'Bulk create users - started (bulk)', 'UserManagement'],
                ['2021-08-24T06:52:22.671Z', 'Bulk create users - finished (bulk)', 'UserManagement'],
                ['2021-08-24T06:52:22.471Z', 'Add user', 'UserManagement'],
                ['2021-08-24T06:52:22.501Z', 'Add user', 'UserManagement'],
                ['2021-08-24T06:52:22.594Z', 'Add user', 'UserManagement'],
                ['2021-08-24T06:52:22.513Z', 'Add user', 'UserManagement'],
                ['2021-08-24T06:54:48.482Z', 'Enable Strong Authentication', 'UserManagement'],
                ['2021-08-24T06:54:48.487Z', 'Update user', 'UserManagement'],
                ['2021-08-24T06:54:33.391Z', 'Enable Strong Authentication', 'UserManagement']
            ]
        }
    ]
}

# 自定义表头
headers = ["tables", "TimeGenerated", "OperationName", "Category"]
table_data = []

# 遍历提取数据
for table in raw_data.get("tables", []):
    table_name = table.get("name", "")
    for row in table.get("rows", []):
        # 组装每行数据:表名 + 行原始数据
        full_row = [table_name] + row
        table_data.append(full_row)

# 方式1:输出Markdown格式表格
print("| " + " | ".join(headers) + " |")
print("| " + " | ".join(["---"] * len(headers)) + " |")
for row in table_data:
    print("| " + " | ".join(row) + " |")

# 方式2:导出为CSV文件
with open("output_table.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(headers)
    writer.writerows(table_data)

输出示例(前3行)

tablesTimeGeneratedOperationNameCategory
PrimaryResult2021-08-24T04:08:01.966ZRestore applicationApplicationManagement
PrimaryResult2021-08-24T06:52:22.14ZBulk create users - started (bulk)UserManagement
PrimaryResult2021-08-24T06:52:22.671ZBulk create users - finished (bulk)UserManagement

内容的提问来源于stack exchange,提问作者김기기돌

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 04:30:04