MongoDB 对象序列化为 JSON
我正在尝试在 HTTP 响应中发送回 JSON 编码的 MongoDB 对象。我已经关注了其他几个类似的问题,但仍然遗漏了一些东西。没有抛出异常,但我在浏览器中得到了一个神秘的
响应。我确信这很简单,但任何帮助将不胜感激。
函数:
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 ))
我使用的是Python 2.4、pymongo、simplejson。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在较新版本的
simplejson
(以及 Python 2.7 中的json
模块)中,您可以在子类中实现default
方法:然后您可以使用编码器使用
MongoEncoder().encode(obj)
或json.dumps(obj, cls=MongoEncoder)
。In newer versions of
simplejson
(and thejson
module in Python 2.7) you implement thedefault
method in your subclasses:You could then use the encoder with
MongoEncoder().encode(obj)
orjson.dumps(obj, cls=MongoEncoder)
.