json - 如何将每个文档的 json 拆分为多个文件

标签 json

我有一个包含数千个文档的大型 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/

相关文章:

ios - JSON 很好地进入字典,但 objectForKey 错误

json - 通过 webhook 和 PS 脚本触发的 MS Teams 警报不想解析多行文本

c# - 如何使用 Json.NET StringEscapeHandling.EscapeNonAscii

java - 如何保存Pojo Gson中不存在的字段

php - 当我将JSon文件写入数据库时​​,字符出现困惑

json - 将特定的 JSON 字段写入文件

javascript - C# WebMethod - 发送和接收相同的自定义对象作为参数

javascript - 将选定的数据发送回原始窗口

visual-studio - Visual Studio : JSON visualizer when debugging

php - jQuery AJAX 调用两次