MongoDB Object Serialized as JSON

Donnie picture Donnie · Jun 6, 2011 · Viewed 9.3k times · Source

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 are thrown, but I get a cryptic <api.views.MongoEncoder object at 0x80a0c02c> response in the browser. I'm sure it's something simple, but any help would be appreciated.

Function:

from django.utils.simplejson import JSONEncoder
from pymongo.objectid import ObjectId

class MongoEncoder( JSONEncoder ):
     def _iterencode( self, o, markers = None ):
          if isinstance( o, ObjectId ):
               return """ObjectId("%s")""" % str(o)
          else:
               return JSONEncoder._iterencode(self, o, markers)

views.py:

user = User({
    's_email': request.GET.get('s_email', ''),
    's_password': request.GET.get('s_password', ''),
    's_first_name': request.GET.get('s_first_name', ''),
    's_last_name': request.GET.get('s_last_name', ''),
    'd_birthdate': request.GET.get('d_birthdate', ''),
    's_gender': request.GET.get('s_gender', ''),
    's_city': request.GET.get('s_city', ''),
    's_state': request.GET.get('s_state', ''),
})

response = {
    's_status': 'success',
    'data': user
}
return HttpResponse(MongoEncoder( response ))

I'm on Python 2.4, pymongo, simplejson.

Answer

zeekay picture zeekay · Jun 6, 2011

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).