-
-
Save nguyenbathanh/792fb6400bbf125b86d02f5a476d14ec to your computer and use it in GitHub Desktop.
Mongoengine JSON encoder
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 json | |
from collections import Iterable | |
from bson import ObjectId | |
from datetime import datetime | |
class MongoengineEncoder(json.JSONEncoder): | |
""" | |
The default JSON encoder that ships with Mongoengine (the to_json method | |
exposed on Document instances) makes some odd choices. Datetime objects | |
are nested on a $date property, ObjectIds are nested on an $oid property, | |
etc. It makes for a confusing interface when you're serializing obejcts for, | |
say, a JavaScript application. | |
This borrows heavily from an abandoned Flask extension called Flask-Views | |
https://github.com/brocaar/flask-views/blob/master/flask_views/db/mongoengine/json.py | |
""" | |
def default(self, obj): | |
if isinstance(obj, Iterable): | |
out = {} | |
for key in obj: | |
out[key] = getattr(obj, key) | |
return out | |
if isinstance(obj, ObjectId): | |
return unicode(obj) | |
if isinstance(obj, datetime): | |
return str(obj) | |
return json.JSONEncoder.default(self, obj) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment