防止Flask jsonify对数据进行排序 [英] Prevent Flask jsonify from sorting the data

查看:589
本文介绍了防止Flask jsonify对数据进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次使用jsonify时,都会得到按字母顺序排序的JSON键.我不希望按键排序.我可以禁用在jsonify中完成的排序吗?

Each time I use jsonify, I get the JSON keys sorted alphabetically. I don't want the keys sorted. Can I disable the sorting done in jsonify?

from flask import request, jsonify

@app.route('/', methods=['POST'])
def index():
    json_dict = request.get_json()
    user_id = json_dict['user_id']
    permissions = json_dict['permissions']
    data = {'user_id': user_id, 'permissions': permissions}
    return jsonify(data)

推荐答案

是的,您可以使用config属性进行修改:

Yes, you can modify this using the config attribute:

app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False

但是,请注意,在文档中明确警告了这一点:

However, note that this is warned against explicitly in the documentation:

默认情况下,Flask将以密钥的方式序列化JSON对象 被订购.这样做是为了确保独立于 字典的哈希种子,返回值将与非一致 垃圾外部HTTP缓存.您可以通过以下方式覆盖默认行为: 更改此变量.不建议这样做,但可能会给您一个 性能提高的可缓存性成本上.

By default Flask will serialize JSON objects in a way that the keys are ordered. This is done in order to ensure that independent of the hash seed of the dictionary the return value will be consistent to not trash external HTTP caches. You can override the default behavior by changing this variable. This is not recommended but might give you a performance improvement on the cost of cacheability.

这篇关于防止Flask jsonify对数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆