0

I am trying to dump a collection to .json file and looked into previous discussions and the solution doesn't seem to work for some reason.

Link : How to dump a collection to json file using pymongo

I am using Python3 and following the solution :

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: name 'json_util' is not defined

1 Answer 1

0

Currently you are importing only son.json_util.dumps You have to import bson.json_util in order to use json_util.default

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.