MongoDB Object Serialized as JSON

半城伤御伤魂 提交于 2019-11-30 11:10:02

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/6255387/mongodb-object-serialized-as-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!