gpt4 book ai didi

python - 防止 Flask jsonify 对数据进行排序

转载 作者:IT老高 更新时间:2023-10-28 20:59:49 26 4
gpt4 key购买 nike

每次我使用 jsonify 时,我都会得到按字母顺序排序的 JSON 键。我不希望对键进行排序。我可以禁用 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 属性来修改它:

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

但是,请注意,documentation 中明确警告了这一点。 :

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.

关于python - 防止 Flask jsonify 对数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43263356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com