【发布时间】:2019-03-23 13:38:07
【问题描述】:
我想将多个 JSON 文件合并到一个文件中。所有这些文件都具有相同的结构。例如,我创建了三个如下所示的文件:
ExampleFile_1
{
"items": [
{
"answers": [
{
"creation_date": 1538172165
},
{
"creation_date": 1538172205
},
{
"creation_date": 1538172245
}
],
"creation_date": 1538172012,
"question_id": 52563137
}
]
}
ExampleFile_2
{
"items": [
{
"answers": [
{
"creation_date": 1538326991
}
],
"creation_date": 1538172095,
"question_id": 52563147
},
{
"answers": [
{
"creation_date": 1538180453
}
],
"creation_date": 1538172112,
"question_id": 52563150
}
]
}
ExampleFile_3
{
"items": [
{
"answers": [
{
"creation_date": 1538326991
}
],
"creation_date": 1538172095,
"question_id": 52563147
}
]
}
现在我想将"items" 列表中的所有三个文件合并到一个文件中,然后如下所示:
merged_json.json
{
"items": [
{
"answers": [
{
"creation_date": 1538172165
},
{
"creation_date": 1538172205
},
{
"creation_date": 1538172245
}
],
"creation_date": 1538172012,
"question_id": 52563137
},
{
"answers": [
{
"creation_date": 1538326991
}
],
"creation_date": 1538172095,
"question_id": 52563147
},
{
"answers": [
{
"creation_date": 1538180453
}
],
"creation_date": 1538172112,
"question_id": 52563150
},
{
"answers": [
{
"creation_date": 1538326991
}
],
"creation_date": 1538172095,
"question_id": 52563147
}
]
}
所以像上面一样,"items" 应该被连接起来。
我已经尝试想出一个解决方案,但无法弄清楚。 这是我到目前为止得到的:
read_files = glob.glob("ExampleFile*.json")
output_list = []
for f in read_files:
with open(f, "rb") as infile:
output_list.append(json.load(infile))
all_items = []
for json_file in output_list:
all_items += json_file['items']
textfile_merged = open('merged_json.json', 'w')
textfile_merged.write(str(all_items))
textfile_merged.close()
不幸的是,这给我留下了一个混乱的 json 文件,它只包含 "items" 中的字典。
如何创建像merged_json.json 这样的文件?
提前致谢。
【问题讨论】:
标签: json python-3.x list dictionary merge