Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Flask jsonify from sorting the data

Tags:

python

json

flask

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) 
like image 678
Athul Muralidharan Avatar asked Apr 06 '17 18:04

Athul Muralidharan


People also ask

Does Flask automatically Jsonify?

No, returning a dict in Flask will not apply jsonify automatically.

What does Jsonify do in Flask?

jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data.


1 Answers

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.

like image 84
juanpa.arrivillaga Avatar answered Oct 04 '22 15:10

juanpa.arrivillaga