MongoDB Object Serialized as JSON
Asked Answered
I

1

6

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.

Infrequency answered 6/6, 2011 at 16:53 Comment(0)
A
18

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

Autosuggestion answered 6/6, 2011 at 17:31 Comment(3)
If you can't find pymongo.objectid, try bson.objectid.Wendiwendie
Based on this answer, stackoverflow.com/a/10401553, ObjectID is no longer in pymongo.object id. Instead, use: import bson.objectidColson
Also, you can use the bson dumps that handle ObjectId from bson.json_util import dumps see https://mcmap.net/q/141730/-typeerror-objectid-39-39-is-not-json-serializableAdversary

© 2022 - 2024 — McMap. All rights reserved.