如何使用 pymongo 将集合转储到 json 文件

Anh*_*hNg 7 python json mongodb pymongo-3.x

我正在尝试将集合转储到 .json 文件,但在查看 pymongo 教程后,我找不到任何与之相关的内容。

教程链接:https : //api.mongodb.com/python/current/tutorial.html

gar*_*ryj 18

接受的解决方案会生成无效的 JSON。它会导致,在右方括号之前出现尾随逗号]。JSON 规范不允许尾随逗号。请参阅此答案和此参考。

为了构建已接受的解决方案,我使用了以下内容:

from bson.json_util import dumps
from pymongo import MongoClient
import json

if __name__ == '__main__':
    client = MongoClient()
    db = client.db_name
    collection = db.collection_name
    cursor = collection.find({})
    with open('collection.json', 'w') as file:
        json.dump(json.loads(dumps(cursor)), file)
Run Code Online (Sandbox Code Playgroud)


小智 10

只需获取所有文件并将它们保存到文件中,例如:

from bson.json_util import dumps
from pymongo import MongoClient

if __name__ == '__main__':
    client = MongoClient()
    db = client.db_name
    collection = db.collection_name
    cursor = collection.find({})
    with open('collection.json', 'w') as file:
        file.write('[')
        for document in cursor:
            file.write(dumps(document))
            file.write(',')
        file.write(']')
Run Code Online (Sandbox Code Playgroud)

  • 这会产生如下错误:“TypeError:类型为‘ObjectId’的对象不是 JSON 可序列化的” (9认同)
  • 这实际上会产生无效的 JSON,因为 `file.write(']')` 之前的最后一个 `file.write(',')` 将导致文件 `,]` 无效。 (6认同)
  • 得到相同的“TypeError”。您可以通过导入“from bson.json_util import dumps”替换“file.write(json.dumps(document))”并将该行替换为“file.write(dumps(document))”来解决该问题[了解更多]( /sf/ask/1161032631/) (3认同)