防止Flaskjsonify对d进行分类

2024-05-17 02:35:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: fromidjsonpermissionsdata排序顺序request
1条回答
网友
1楼 · 发布于 2024-05-17 02:35:10

是的,您可以使用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.

相关问题 更多 >