我有一个包含数千个文档的大型 json 文件:
[
{
"_id": "document1",
"fields": [ ... ]
},
{
"_id": "document2",
"fields": [ ... ]
},
...
]
我想拆分此 json 文件,以便每个 json 文件包含一个文档,并相应地命名它们:
document1.json, document2.json, ...
例如,document1.json
将包含:
{
"_id": "document1",
"fields": [ ... ]
}
我对 jq API 不了解,我正在努力寻找答案(我找到了 similar question ,但略有不同:( )
最佳答案
这是针对您的问题的 Python 解决方案。
Don't forget to change the
in_file_path
to the location of your big JSON file.
import json
in_file_path='path/to/file.json' # Change me!
with open(in_file_path,'r') as in_json_file:
# Read the file and convert it to a dictionary
json_obj_list = json.load(in_json_file)
for json_obj in json_obj_list:
filename=json_obj['_id']+'.json'
with open(filename, 'w') as out_json_file:
# Save each obj to their respective filepath
# with pretty formatting thanks to `indent=4`
json.dump(json_obj, out_json_file, indent=4)
旁注:我在 Python3 中运行了这个,它应该也可以在 Python2 中工作
关于json - 如何将每个文档的 json 拆分为多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46534569/