在Python中将数据结构转储为JSON会引发不可排序类型str和builtin_function_or_method



我试图在数据结构上调用Flask的jsonify,但我得到TypeError: unorderable types: str() < builtin_function_or_method()。如何修复此错误?

bucketlists = [{
    'id': 1,
    'name': "BucketList1",
    'items': [{
        id: 1,
        'name': "I need to do X",
        'date_created': "2015-08-12 11:57:23",
        'date_modified': "2015-08-12 11:57:23",
        'done': False
    }],
    'date_created': "2015-08-12 11:57:23",
    'date_modified': "2015-08-12 11:57:23",
    'created_by': "1113456"
}]
@app.route('/bucketlists/', methods=['GET'])
def get_bucketlists():
    return jsonify({'bucketlists': bucketlists})

id是Python内置函数;jsonify不能序列化它,您需要用引号包装字典键以使其成为字符串:

bucketlists = [{
    'id': 1,
    'name': "BucketList1",
    'items': [{
        'id': 1, # -----> Here
        'name': "I need to do X",
        'date_created': "2015-08-12 11:57:23",
        'date_modified': "2015-08-12 11:57:23",
        'done': False
    }],
    'date_created': "2015-08-12 11:57:23",
    'date_modified': "2015-08-12 11:57:23",
    'created_by': "1113456"
}]

另外,您需要添加双下划线来访问模块的名称:

app = Flask(__name__)

最新更新