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

Python实现JSON与CSV互转 嵌套字典导出键值对格式CSV问题咨询

报错原因

你代码报错是因为data["d"].items()返回的是dict_items类型的键值对元组迭代对象,而pd.DataFrame.from_dict的orient="index"参数要求传入标准字典结构,二者不匹配导致调用失败。

实现方案

1. JSON转CSV(保留原始结构,支持完整还原)

该实现会读取JSON中所有键值对,写入CSV的同一列,每行格式为key value,同时插入外层键标记方便后续还原结构:

import json
import pandas as pd

# 读取原始JSON
with open('some.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

output_rows = []
for outer_key, inner_dict in data.items():
    # 插入外层键标记,还原时用于识别分组
    output_rows.append(f"##outer:{outer_key}")
    for inner_key, value in inner_dict.items():
        output_rows.append(f"{inner_key} {value}")

# 写入CSV,无表头无索引
df = pd.DataFrame(output_rows)
df.to_csv("data.csv", index=False, header=False, encoding='utf-8')

生成的CSV内容效果如下:

##outer:d
a one
b two
c three
##outer:z
j eleven
k twenty
l forty

2. CSV转回JSON

该实现可以读取上述CSV文件,100%还原为原始结构的JSON文件:

import json
import pandas as pd

# 读取CSV
df = pd.read_csv('data.csv', header=None, encoding='utf-8')
rows = df[0].tolist()

restored_data = {}
current_outer_key = None

for row in rows:
    # 识别外层键标记
    if row.startswith("##outer:"):
        current_outer_key = row.split(":", 1)[1]
        restored_data[current_outer_key] = {}
        continue
    # 拆分键值对
    inner_key, value = row.split(" ", 1)
    restored_data[current_outer_key][inner_key] = value

# 写入还原后的JSON
with open("restored.json", "w", encoding='utf-8') as f:
    json.dump(restored_data, f, indent=2, ensure_ascii=False)

如果你不需要保留原始JSON的外层键结构,仅需要把所有键值对合并为一个字典存储,可以去掉外层键标记的相关代码,直接收集所有{inner_key} {value}格式的行即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 01:15:03