MongoDB Object Serialized as JSON

后端 未结 1 1243
被撕碎了的回忆
被撕碎了的回忆 2020-12-24 09:49

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

相关标签:
1条回答
  • 2020-12-24 10:37

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

    0 讨论(0)
提交回复
热议问题