Python解析两个同结构JSON文件并按交替顺序写入CSV的实现方法
实现代码
你可以直接使用下方修改后的代码,只需替换两个JSON文件的路径为你实际的路径即可:
#!/usr/bin/env python3 import json from itertools import zip_longest # 替换为你实际的两个JSON文件路径 json_path1 = "/root/test1.json" json_path2 = "/root/test2.json" output_csv_path = "/tmp/tmp.csv" # 读取两个JSON文件 with open(json_path1, "r", encoding="utf-8") as f1, open(json_path2, "r", encoding="utf-8") as f2: data1 = json.load(f1) data2 = json.load(f2) # 写入CSV文件 with open(output_csv_path, "w", encoding="utf-8") as csv_file: # 写入表头 csv_file.write("Source IP;Source Port;Destination IP;Destination Port \n") # 交替遍历两个JSON的条目,zip_longest可处理两个文件条目数量不一致的场景 for item1, item2 in zip_longest(data1, data2): # 写入第一个JSON的当前条目(存在才写) if item1: src_ip = item1["source_ip"] src_port = str(item1["source_port"]) dst_ip = item1["destination_ip"] dst_port = str(item1["destination_port"]) line = f"{src_ip};{src_port};{dst_ip};{dst_port}\n" csv_file.write(line) # 写入第二个JSON的当前条目(存在才写) if item2: src_ip = item2["source_ip"] src_port = str(item2["source_port"]) dst_ip = item2["destination_ip"] dst_port = str(item2["destination_port"]) line = f"{src_ip};{src_port};{dst_ip};{dst_port}\n" csv_file.write(line)
关键修改说明
- 引入
zip_longest工具同时遍历两个JSON的条目,天然满足交替写入的需求,同时兼容两个JSON条目数量不一致的场景:如果其中一个JSON的条目更多,多出来的条目会自动按顺序追加在CSV末尾,不会丢失数据。 - 所有文件操作统一使用
with上下文管理器,无需手动调用close()方法关闭文件,避免资源泄漏。 - 保留了你原有的字段解析逻辑,仅调整了写入顺序,和你的原有业务逻辑完全兼容。
内容的提问来源于stack exchange,提问作者Alex Rebell
相关产品推荐
相关产品推荐

