Last active
March 20, 2020 13:59
-
-
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
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
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