Skip to content

Instantly share code, notes, and snippets.

@gati
Created September 7, 2014 00:46
Show Gist options
  • Save gati/5a247d25b2a667055261 to your computer and use it in GitHub Desktop.
Save gati/5a247d25b2a667055261 to your computer and use it in GitHub Desktop.
Mongoengine JSON encoder
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)
@nguyenbathanh
Copy link

Thanks!

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