JSON (JavaScript Object Notation): 是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。
CSV (Comma-Separated Values): 是一种常见的文件格式,用于存储表格数据(如电子表格或数据库),其结构简单,可以很容易地被许多程序读取和写入。
假设我们有以下两个JSON文件:
file1.json
[
{"name": "Alice", "age": 30, "city": "New York"},
{"name": "Bob", "age": 25, "city": "Los Angeles"}
]
file2.json
[
{"name": "Charlie", "age": 35, "city": "Chicago"},
{"name": "David", "age": 40, "city": "Houston"}
]
我们可以使用Python脚本来合并这些JSON文件并将其转换为CSV格式。
Python脚本示例
import json
import csv
# 读取多个JSON文件
json_files = ['file1.json', 'file2.json']
all_data = []
for file in json_files:
with open(file, 'r') as f:
data = json.load(f)
all_data.extend(data)
# 将合并后的数据写入CSV文件
csv_file = 'output.csv'
keys = all_data[0].keys()
with open(csv_file, 'w', newline='') as output_file:
dict_writer = csv.DictWriter(output_file, keys)
dict_writer.writeheader()
dict_writer.writerows(all_data)
运行上述脚本后,会生成一个名为output.csv
的文件,内容如下:
name,age,city
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago
David,40,Houston
问题1: JSON文件格式不一致。
问题2: 大量数据导致内存不足。
通过上述方法,可以有效地组合多个JSON文件并转换为CSV格式,适用于各种数据处理需求。
领取专属 10元无门槛券
手把手带您无忧上云