如何用Python将含数组对象的JSON转换为指定格式的CSV
处理含数组的JSON转特定格式CSV(适配PostgreSQL导入)
需求背景
我有一个以键值对为主但包含数组的JSON文件,需要转换成特定格式的CSV,方便导入PostgreSQL数据库。JSON内容如下:
{ "name": "Text", "operator_type": [ "one", "two", "three" ], "street": "Mönchhaldenstraße ", "street_nr": "113", "zipcode": "70191", "city": "Stuttgart", "operator_type_id": [ "1", "2", "3" ], "dc_operator_per": [ "100", "", "" ], "input_power": 600.0, "el_power": 800.0, "col_power": 300.0 }
当前转换的问题
我现在用Pandas做简单转换,代码如下:
import pandas as pd data=pd.read_json('export.json') data.to_csv('text.csv') data=pd.read_csv('text.csv')
但转换后,数组的每个元素都会生成新行,非数组字段会重复填充,比如:
name,dc_operator_type,capacity_kwh,export_me Test,Colocation,,600,True Test,,,600,True,
期望的CSV格式
我需要的格式分两种情况:
- 当只有一个数组元素时,所有字段在同一行:
name,dc_operator_type,capacity_kwh,export_me Test,Colocation,,600,True
- 当有多个数组元素时,仅第一行填充所有非数组字段,后续行只填对应数组字段,其余留空:
name,dc_operator_type,capacity_kwh,export_me Test,Colocation,,600,True ,Seconlocation,,,
解决方案
要实现这种格式,需要手动拆分数组字段和非数组字段,逐行构造数据,代码如下:
步骤1:读取并拆分数据
import pandas as pd import json # 读取JSON文件 with open('export.json', 'r', encoding='utf-8') as f: raw_data = json.load(f) # 分离数组类型字段和普通字段 array_cols = {} normal_cols = {} for key, value in raw_data.items(): if isinstance(value, list): array_cols[key] = value else: normal_cols[key] = value # 确定需要生成的行数(取数组字段的最大长度,没有数组则生成1行) total_rows = max(len(v) for v in array_cols.values()) if array_cols else 1
步骤2:构造每行数据
rows = [] for i in range(total_rows): current_row = {} # 普通字段仅第一行填充,后续行留空 if i == 0: current_row.update(normal_cols) else: for col in normal_cols: current_row[col] = "" # 填充对应索引的数组元素,超出数组长度则留空 for col, values in array_cols.items(): current_row[col] = values[i] if i < len(values) else "" rows.append(current_row)
步骤3:导出CSV
# 保持原JSON的字段顺序 all_columns = list(normal_cols.keys()) + list(array_cols.keys()) df = pd.DataFrame(rows, columns=all_columns) # 导出时不包含索引列 df.to_csv('output.csv', index=False, encoding='utf-8')
注意事项
- 代码默认所有数组字段的长度一致,如果有长度不一致的情况,可以根据需求调整(比如给短数组补空值,或者截断长数组)
- 导出的CSV完全符合预期格式,直接就能导入PostgreSQL使用
内容的提问来源于stack exchange,提问作者Ponyo1402
相关产品推荐
相关产品推荐

