5

I am using MongoDB 3.4 and Python 2.7. I have retrieved a document from the database and I can print it and the structure indicates it is a Python dictionary. I would like to write out the content of this document as a JSON file. When I create a simple dictionary like d = {"one": 1, "two": 2} I can then write it to a file using json.dump(d, open("text.txt", 'w')) However, if I replace d in the above code with the the document I retrieve from MongoDB I get the error

ObjectId is not JSON serializable

Suggestions?

2 Answers 2

7

As you have found out, the issue is that the value of _id is in ObjectId.

The class definition for ObjectId is not understood by the default json encoder to be serialised. You should be getting similar error for ANY Python object that is not understood by the default JSONEncoder.

One alternative is to write your own custom encoder to serialise ObjectId. However, you should avoid inventing the wheel and use the provided PyMongo/bson utility method bson.json_util

For example:

from bson import json_util 
import json 

json.dump(json_util.dumps(d), open("text.json", "w"))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Worked great.
1

The issue is that “_id” is actually an object and not natively deserialized. By replacing the _id with a string as in mydocument['_id'] ='123 fixed the issue.

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.