I'm trying to pass sorted dictionary to jsonify() function and then use it from within JS code to take out values. What I see there is that even though I pass correct values, they are reordered by jsonify for some reason.
json_data = {
"11": {
"j_id": "out",
},
"aa": {
"j_id": "in",
},
"bb": {
"j_id": "out",
},
}
jkeys=json_data.keys()
sorted_json = sorted(jkeys, key=lambda x: json_data[x]['j_id'], reverse=False)
new_sorted=OrderedDict()
for rec in sorted_json:
new_sorted[rec]=json_data[rec]
print('sort dict: {}'.format(new_sorted))
The output is correct and I can see proper values which in my case should be: aa, 11, bb
>>> from collections import OrderedDict
>>>
>>> json_data = {
... "11": {
... "j_id": "out",
... },
... "aa": {
... "j_id": "in",
... },
... "bb": {
... "j_id": "out",
... },
... }
>>>
>>> jkeys=json_data.keys()
>>> sorted_json = sorted(jkeys, key=lambda x: json_data[x]['j_id'], reverse=False)
>>>
>>> new_sorted=OrderedDict()
>>> for rec in sorted_json:
... new_sorted[rec]=json_data[rec]
...
>>> print('sort dict: {}'.format(new_sorted))
sort dict: OrderedDict([('aa', {'j_id': 'in'}), ('11', {'j_id': 'out'}), ('bb', {'j_id': 'out'})])
Unfortunately, when I pass this to jsonify() function and then for example console.log() output of flask data, the orderd becomes like that: 11, aa, bb. Additionally to that, I've done some research and found this stackoverflow answer, leading to some good documentation notes which clearly states that setting JSON_SORT_KEYS to False is not recommended way. Then I checked this github issue and it seems that problem is not fully resolved in flask.
What would be the best way to fix it in my case?