MongoDB Object Serialized as JSON

I am trying to send a JSON encoded MongoDB object to my HTTP response. I followed a few other similar questions, but I still missed something. No exceptions are thrown, but I get a critical response <api.views.MongoEncoder object at 0x80a0c02c> in the browser. I am sure this is something simple, but any help would be appreciated.

Functions:

 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.

+6
source share
1 answer

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) 

Then you can use the encoder with MongoEncoder().encode(obj) or json.dumps(obj, cls=MongoEncoder) .

+17
source

Source: https://habr.com/ru/post/889883/


All Articles