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

Python解析嵌套JSON转CSV并新增自定义列报错如何解决?

问题原因
  • 循环逻辑错误:你写的for row in data中,data是加载后的完整JSON字典,直接迭代字典默认只会返回字典的键(也就是字符串code、message、data),对字符串执行row["data"]操作自然会触发类型错误。
  • 表头生成逻辑错误:data["data"].keys()返回的是外层data字段下的数字键(1、2、3...),而你需要的表头是内层每个对象的属性名(id、name、icon等),以及要新增的自定义列。
  • 取值逻辑错误:你需要的内容是data["data"]下所有数字键对应的属性值集合,而非外层JSON的内容。
实现代码

使用csv.DictWriter实现的适配代码如下,完全匹配你要的PowerShell迁移需求和输出格式:

import json
import csv

# 配置路径和自定义列参数,对应PowerShell中的变量可按需修改
jsonfile = "/path/to/your.json"
csvfile = "/path/to/output.csv"
custom1 = "a" # 对应PowerShell的$m
level = "your_level_value" # 对应PowerShell的$l
custom2 = "b" # 对应PowerShell的$a
custom3 = "c" # 对应PowerShell的$r

with open(jsonfile, "r", encoding="utf-8") as f:
    json_data = json.load(f)

# 提取所有有效数据条目
all_items = list(json_data["data"].values())
if not all_items:
    print("JSON中无有效数据")
    exit()

# 生成表头:原有属性 + 自定义新增列
fieldnames = list(all_items[0].keys()) + ["Custom1", "Level", "Custom2", "Custom3"]

with open(csvfile, "w", encoding="utf-8", newline="") as f:
    # QUOTE_ALL参数保证所有字段都用双引号包裹,匹配预期输出格式
    writer = csv.DictWriter(f, fieldnames=fieldnames, quoting=csv.QUOTE_ALL)
    writer.writeheader()
    for item in all_items:
        # 追加自定义列内容
        item.update({
            "Custom1": custom1,
            "Level": level,
            "Custom2": custom2,
            "Custom3": custom3
        })
        writer.writerow(item)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 01:54:08