Dealing with the Type Error: ObjectId(”) is not JSON serializable error when working with MongoDB

When building RESTful APIs that connect to a MongoDB databases, the error below might come up when you attempt to serialize a mongodb record _id:

TypeError: ObjectId('51948e86c25f4b1d1e86c25f') is not JSON serializable

The error is caused by an incompatibility between JSON and the BSON ObjectId data type. One way around this error is to create a custom JSON Encoder that can handle ObjectId data.


import json
from bson import ObjectId

class JSONEncoder(json.JSONEncoder):
    def default(self, item):
        if isinstance(item, ObjectId):
            return str(item)
        return json.JSONEncoder.default(self, item)

 

After creating this encoder, you can then create a custom JSONField that takes advantage of it in your serializers.py file:

class JSONFIeld(serializers.Field):
    def to_representation(self, value):
        try:
            result = json.dumps(
                value, skipkeys=True, 
                allow_nan=True,cls=JSONEncoder
            )
            return result
        except ValueError:
            return ''

 

If you’ll be writing to the database, you’ll also want to implement a .to_internal_value() method to handle conversion into data types that are safe for the database. After doing this, you can use this custom JSONField as a serializer field.