MongoDB Object Serialized as JSON

巧了我就是萌 提交于 2019-11-29 23:22:46

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

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