我有多个JSON文件,如下所示:
foo.json
:
{"Email":["abc@abc.com","aac@abc.com","asd@ac.com"]}
bar.json
:
{"Work": ["Microsoft","Google","Yahoo"]}
我想将所有这些附加在一起而不修改它们: 我正在使用它来追加它们:
import json
import glob
import sys
import os
read_files = glob.glob("*.json")
output_list = []
for f in read_files:
with open(f, "rb") as infile:
output_list.append(json.load(infile))
with open("merged_file.json", "wb") as outfile:
json.dump(output_list, outfile)
这个输出是:
[{"Email":["abc@abc.com","aac@abc.com","asd@ac.com"]},{"Work": ["Microsoft","Google","Yahoo"]}]
这使得输出看起来与输入不同。如何在开头和结尾都没有“[]”,所有键都在同一个JSON对象中?
所需的输出是:
{"Email":["abc@abc.com","aac@abc.com","asd@ac.com"],"Work": ["Microsoft","Google","Yahoo"]}
答案 0 :(得分:1)
您正在构建一个列表,但您的预期输出显示您需要一个JSON对象(Python中的字典)。如果您的输入文件具有唯一键,则需要构建新词典:
import glob
import json
output = {}
for f in glob.glob("*.json"):
with open(f, "rb") as infile:
entry = json.load(infile)
output.update(entry)
with open("merged_file.jsonl", "wb") as outfile:
json.dump(output, outfile)