【Flask Mongodb】typeError: ObjectId('xxx') is not JSON serializable

mogondb的id是ObjectID对象,这个对象是不能被json.dumps序列化的。

bson提供了一个dumps方法,所以比较好的解决方案是用这个方法来代替jsonify。

我建议在utils直接重写一个jsonify来调用,直接把jsonify的源码复制过来就行,不用改。

from bson.json_util import dumps

def jsonify(*args, **kwargs):
    """Copy了jsonify的原始实现,改为使用bson提供的dumps方法"""
    indent = None
    separators = (',', ':')

    if current_app.config['JSONIFY_PRETTYPRINT_REGULAR'] or current_app.debug:
        indent = 2
        separators = (', ', ': ')

    if args and kwargs:
        raise TypeError('jsonify() behavior undefined when passed both args and kwargs')
    elif len(args) == 1:  # single args are passed directly to dumps()
        data = args[0]
    else:
        data = args or kwargs

    return current_app.response_class(
        dumps(data, indent=indent, separators=separators) + '\n',
        mimetype=current_app.config['JSONIFY_MIMETYPE']
    )

注意一下,objectID会被序列化为{'$oid': xxx}的dict,接收方在用的时候要记得取出来。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容