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

标签 python json flask

每次我使用 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/

相关文章:

python - 在列表理解中添加额外的项目

json - 在一个查询中更新多行,但我们期望的输入来自多个数据的 json 对象

json - 从 FireBase JSON swift 中检索自动 ID

javascript - 根据每个值的内容过滤掉 JSON 数组

python - 从 flask restful 端点的另一个目录提供静态 html 文件

python,networkx 2.0 'girvan_newman' 未定义

python - 查找两个$之间的文本并将它们放入列表中

flask - AirPlay 弄乱了本地主机

python - pip 不存在或无法在 virtualenv 中执行

python - 检查字符串是否在 pandas Dataframe 列中,并创建新的 Dataframe