41

Each time I use jsonify, I get the JSON keys sorted alphabetically. I don't want the keys sorted. Can I disable the sorting done in 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)
davidism
  • 110,080
  • 24
  • 357
  • 317
Athul Muralidharan
  • 643
  • 1
  • 8
  • 16

1 Answers1

87

Yes, you can modify this using the config attribute:

app = Flask(__name__)
app.config['JSON_SORT_KEYS'] = False

However, note that this is warned against explicitly in the 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.

juanpa.arrivillaga
  • 77,035
  • 9
  • 115
  • 152
  • 8
    It should be noted as of Python 3.6, dicts retain their insertion order so the argument from the docs doesn't apply anymore in that general sense. – hynek Nov 28 '19 at 14:33
  • 3
    I think the answer should be updated because this is an important sidenote from @hynek. – Ri1a Dec 03 '19 at 12:47
  • @hynek still seems to work on my version at python v3.7.3 & Flask v1.1.1 – Cory C Feb 25 '20 at 04:08
  • 1
    Nobody said that it doesn’t work anymore; just that the rational for sorting keys that is in the docs quote is nil nowadays. Leaving it there could be confusing to new users. – hynek Feb 26 '20 at 05:04
  • @hynek I need my dict be in reverse order based on keys..so i do the same and return the response..but when passed through jsonify its back to its same order. How can I overcome this issue? – Dinesh Apr 13 '20 at 10:42