使用 Flask 的 jsonify() 是不可能的,但只使用普通的香草 json.dumps() 是可能的。唯一的问题是您必须让内容长度匹配,因为这是在响应标头中设置的:
import json
from collections import OrderedDict
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/unordered")
def unordered_dict():
d = OrderedDict([('e',1),('d',2),('c',3),('b',4),('a',5)])
output = jsonify(d)
return output
@app.route("/ordered")
def ordered_dict():
d = OrderedDict([('e',1),('d',2),('c',3),('b',4),('a',5)])
response = json.dumps(d)
placeholder = '_'*(len(response)-2) # Create a placeholder, -2 due to ""
output = jsonify(placeholder) # This needs to be the same length as the response
output.response[0] = response + '\n' # Replace with the actual response
return output
默认情况下,第一个将按字母键顺序返回,如果app.config['JSON_SORT_KEYS'] = False,则按随机顺序返回。第二个应该按指定的顺序返回键。
警告:正如其他人所指出的,JSON 规范不需要顺序。但是,似乎大多数浏览器无论如何都尊重顺序,因此可以在顺序很好但不重要的情况下使用它。如果顺序很重要,那么您唯一的选择是在转换为 JSON 之前转换为列表。
(注意:在https://github.com/pallets/flask/issues/1877 之前,Content-Length 没有明确设置,所以要简单得多!)