- 正常的 python dict 是按字母顺序排序的,所以要使用 OrderedDict 来自定义顺序
import collections | |
data = collections.OrderedDict() | |
data['b'] = 3 | |
data['a'] = 1 | |
data = jsonify(d) | |
return make_response(data, 200) |
- flask 框架的 jsonify 默认也是按字母顺序排序的,所以在 flask 项目启动时添加一个启动参数
app.config["JSON_SORT_KEYS"] = False |
官方文档解释如下:
Sort the keys of JSON objects alphabetically. This is useful for caching because it ensures the data is serialized the same way no matter what Python’s hash seed is. While not recommended, you can disable this for a possible performance improvement at the cost of caching.
# 参考
https://github.com/pallets/flask/issues/974
https://flask.palletsprojects.com/en/2.0.x/config/#JSON_SORT_KEYS