【问题标题】:How to dump a collection to JSON file using Pymongo/json.dumps如何使用 Pymongo/json.dumps 将集合转储到 JSON 文件
【发布时间】:2020-01-02 11:18:11
【问题描述】:

我正在尝试将集合转储到 .json 文件并查看以前的讨论,但由于某种原因,该解决方案似乎不起作用。

链接:How to dump a collection to json file using pymongo

我正在使用 Python3 并遵循解决方案:

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

client = MongoClient()
db = client.db_name
collection = db.collection_name

def writeToJSONFile(collection):
   cursor = collection.find({})
   file = open("collection.json", "w")
   file.write('[')

   qnt_cursor = 0
   for document in cursor:
       qnt_cursor += 1
       num_max = cursor.count()
       if (num_max == 1):
           file.write(json.dumps(document, indent=4, default=json_util.default))
       elif (num_max >= 1 and qnt_cursor <= num_max-1):
           file.write(json.dumps(document, indent=4, default=json_util.default))
           file.write(',')
       elif (qnt_cursor == num_max):
           file.write(json.dumps(document, indent=4, default=json_util.default))
   file.write(']')
   return file

NameError: 名称 'json_util' 未定义

【问题讨论】:

    标签: python-3.x mongodb pymongo


    【解决方案1】:

    目前您只导入了son.json_util.dumps 你必须import bson.json_util 为了使用json_util.default

    【讨论】:

      猜你喜欢
      • 2018-08-15
      • 1970-01-01
      • 2018-10-19
      • 2019-01-12
      • 2014-12-13
      • 1970-01-01
      • 1970-01-01
      • 2013-06-07
      • 2014-08-28
      相关资源
      最近更新 更多