Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@nguyenbathanh
Last active March 20, 2020 13:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nguyenbathanh/d5014f5568699ba111b2f0eb067eada8 to your computer and use it in GitHub Desktop.
Save nguyenbathanh/d5014f5568699ba111b2f0eb067eada8 to your computer and use it in GitHub Desktop.
MongoEngineJSONEncoder. Dump the data in a BaseDocument ,QuerySet of Mongo documents to JSON
import datetime
import json
from bson import ObjectId
from mongoengine.base import BaseDocument
from mongoengine.queryset import QuerySet
class MongoengineEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, BaseDocument):
return obj.to_mongo()
if isinstance(obj, QuerySet):
return list(obj)
if isinstance(obj, ObjectId):
return str(obj)
if isinstance(obj, datetime.datetime):
return obj.isoformat()
return json.JSONEncoder.default(self, obj)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment