将更复杂的JSON转换为CSV可以通过以下步骤实现:
json
模块,将JSON数据加载为对象或字典。csv
模块,将CSV数据写入文件。以下是示例代码(使用Python语言和相关库):
import json
import csv
def convert_json_to_csv(json_data):
# 1. 解析JSON数据
data = json.loads(json_data)
# 2. 遍历JSON数据
rows = []
process_json(data, rows)
# 3. 构建CSV表头
headers = list(set([key for row in rows for key in row.keys()]))
# 4. 构建CSV数据行
csv_rows = [headers]
for row in rows:
csv_row = [row.get(header, "") for header in headers]
csv_rows.append(csv_row)
# 5. 写入CSV文件
with open('output.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerows(csv_rows)
def process_json(data, rows, current_row=None, current_path=""):
if isinstance(data, dict):
for key, value in data.items():
new_path = f"{current_path}.{key}" if current_path else key
process_json(value, rows, current_row, new_path)
elif isinstance(data, list):
for index, item in enumerate(data):
new_row = current_row.copy() if current_row else {}
new_path = f"{current_path}[{index}]" if current_path else f"[{index}]"
process_json(item, rows, new_row, new_path)
else:
if current_row is not None:
current_row[current_path] = data
else:
rows.append({current_path: data})
# 示例JSON数据
json_data = """
{
"employees": [
{
"firstName": "John",
"lastName": "Doe",
"email": "john@example.com",
"phoneNumbers": [
{
"type": "home",
"number": "1234567890"
},
{
"type": "work",
"number": "0987654321"
}
]
},
{
"firstName": "Jane",
"lastName": "Smith",
"email": "jane@example.com",
"phoneNumbers": [
{
"type": "home",
"number": "9876543210"
},
{
"type": "work",
"number": "0123456789"
}
]
}
]
}
"""
convert_json_to_csv(json_data)
在上述示例代码中,convert_json_to_csv
函数接受JSON数据作为输入,然后根据上述步骤将其转换为CSV格式的文件。JSON数据中包含了一个员工列表,每个员工有一些基本信息和电话号码。最终生成的CSV文件如下:
firstName,lastName,email,phoneNumbers[0].type,phoneNumbers[0].number,phoneNumbers[1].type,phoneNumbers[1].number
John,Doe,john@example.com,home,1234567890,work,0987654321
Jane,Smith,jane@example.com,home,9876543210,work,0123456789
注意:由于JSON数据的复杂性可能会有很多不同的结构,上述代码只是一个简单示例。如果JSON数据结构更加复杂,可能需要根据实际情况进行相应的修改和调整。
领取专属 10元无门槛券
手把手带您无忧上云