如何将JSON中的多个字典垂直写入CSV并支持回读为JSON
解决方案
你的需求是输出带顶层字典名的非对称CSV结构,同时支持反向解析回JSON,用Python原生的json和csv模块处理比pandas更方便,完整实现如下:
1. JSON转目标CSV
import json import csv # 读取JSON文件 with open("some.json", "r", encoding="utf-8") as f: data = json.load(f) # 写入CSV with open("some.csv", "w", encoding="utf-8", newline="") as f: writer = csv.writer(f) for dict_name, kv_pairs in data.items(): # 先写字典名,单独占一行 writer.writerow([dict_name]) # 逐行写键值对 for k, v in kv_pairs.items(): writer.writerow([k, v])
运行后生成的CSV完全符合你给出的预期格式,且如果键/值包含逗号会自动加引号转义,不会破坏结构。
2. CSV反向转JSON
import json import csv data = {} current_dict = None with open("some.csv", "r", encoding="utf-8") as f: reader = csv.reader(f) for row in reader: # 空行跳过 if not row: continue # 行长度为1说明是顶层字典名 if len(row) == 1: current_dict = row[0] data[current_dict] = {} # 行长度为2说明是键值对 elif len(row) == 2 and current_dict is not None: k, v = row data[current_dict][k] = v # 写入回JSON文件 with open("some.json", "w", encoding="utf-8") as f: json.dump(data, f, indent=2, ensure_ascii=False)
你在CSV里新增的键值对只要对应到正确的字典名下,运行这段代码就会自动同步到原JSON文件中。
注意事项
- 标准JSON要求字符串用双引号包裹,如果你手里的JSON文件用的是单引号(示例里的写法),读取时可以用
ast.literal_eval替代json.load处理:import ast with open("some.json", "r", encoding="utf-8") as f: data = ast.literal_eval(f.read()) - 如果要保留原JSON的其他顶层非字典字段,可以自行扩展判断逻辑。
内容的提问来源于stack exchange,提问作者iamgroot
相关产品推荐
相关产品推荐

