Skip to content

Instantly share code, notes, and snippets.

@corydolphin
Last active August 9, 2021 17:57
Show Gist options
  • Save corydolphin/11005158 to your computer and use it in GitHub Desktop.
Save corydolphin/11005158 to your computer and use it in GitHub Desktop.
Fix: TypeError: ObjectId is not JSON serializable: A Flask JSONEncoder for Mongoengine documents. Specifically useful for use with Flask-Mongoengine.
from flask import Flask
from flask.json import JSONEncoder
from bson import json_util
from mongoengine.base import BaseDocument
from mongoengine.queryset.base import BaseQuerySet
class MongoEngineJSONEncoder(JSONEncoder):
def default(self,obj):
if isinstance(obj,BaseDocument):
return json_util._json_convert(obj.to_mongo())
elif isinstance(obj,BaseQuerySet):
return json_util._json_convert(obj.as_pymongo())
return JSONEncoder.default(self, obj)
'''
To use:
from mongoengine_jsonencoder import MongoEngineJsonEncoder
app = Flask(__name__)
app.json_encoder = MongoEngineJSONEncoder
Now Flask's jsonify works for Mongoengine querysets, and documents.
'''
@hamdifourati
Copy link

I think you should use : from mongoengine_jsonencoder import MongoEngineJSONEncoder instead.

@ricardotenv
Copy link

Thank you that saved me!

@anaplopes
Copy link

from bson.objectid import ObjectId
from core.services.db_connection import DbConnectionService

class DbExecutionService:
     def __init__(self):
        self.db = DbConnectionService()

     def list(self, collection, search):
        session = self.db.create_connection(collection)
        return list(map(lambda row: {i: str(row[i]) if isinstance(row[i], ObjectId) else row[i] for i in row}, session.find(search))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment