how to keep order of sorted dictionary passed to jsonify() function?
JSON objects are unordered structures, and your browser could easily end up discarding the order of your JSON keys again.
From the JSON standard:
An object is an unordered set of name/value pairs.
Bold emphasis mine. To remain standards compliant, use a list (JSON array) to capture a specific order.
That said, Flask can be made to preserve the order you set with OrderedDict
.
Disable sorting app-wide, with
JSON_SORT_KEYS = False
.With this setting at the default
True
,jsonify()
sorts keys to provide stable HTTP responses that are cacheable. The documentation warns against disabling this only to make you aware of the downside of setting this toFalse
.However, if you are using Python 3.6 or newer this concern doesn't actually play because as of that version the built-in
dict
type also preserves insertion order, and so there is no problem with the order changing from one Python run to the next.Instead of using
jsonify()
, useflask.json.dumps()
directly, and create your ownResponse
object. Pass insort_keys=False
:from flask import json response = current_app.response_class( json.dumps(new_sorted, sort_keys=False), mimetype=current_app.config['JSONIFY_MIMETYPE'])
Add this config line to your code after the app definition:
app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False
By default, keys from json are sorted to true. You need to override this in your project config as follows:
app.config['JSON_SORT_KEYS'] = False