Last active
August 9, 2021 17:57
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. | |
''' |
Thank you that saved me!
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
I think you should use :
from mongoengine_jsonencoder import MongoEngineJSONEncoder
instead.