【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,接收方在用的时候要记得取出来。

你可能感兴趣的:(【Flask Mongodb】typeError: ObjectId('xxx') is not JSON serializable)