我想将多个 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
的文件?
提前致谢。
原文由 julius.d 发布,翻译遵循 CC BY-SA 4.0 许可协议
您正在使用
json
模块将 JSON 文件转换为 Python 对象,但您没有使用该模块将这些 Python 对象转换 回 JSON。而不是最后这个尝试这个:
(请注意,这还将
all_items
数组包装在字典中,以便您获得预期的输出,否则输出将是一个 JSON 数组,而不是具有"items"
键的对象).