I\'m attempting to send a JSON encoded MongoDB object back in my HTTP response. I\'ve followed several other similar questions but am still missing something. No exceptions
In newer versions of simplejson
(and the json
module in Python 2.7) you implement the default
method in your subclasses:
from json import JSONEncoder
from pymongo.objectid import ObjectId
class MongoEncoder(JSONEncoder):
def default(self, obj, **kwargs):
if isinstance(obj, ObjectId):
return str(obj)
else:
return JSONEncoder.default(obj, **kwargs)
You could then use the encoder with MongoEncoder().encode(obj)
or json.dumps(obj, cls=MongoEncoder)
.