I have an inflexible requirement to preserve the order of the keys output by an API. I have the data as a python dict and pass it to the jinja2 template as context like so:
....
return templates.TemplateResponse(
"sat.html",
context={
"request": request,
"address": address,
"json_out": json_out, # this is a dict with correct order
"timing": timing,
"title_text": title_text,
},
)
If I just use {{ json_out }} in the template, I find that the order is preserved. If I use {{ json_out | tojson }} (because I am interested in passing this to javascript), the keys get sorted. Why?
See this example:

Code used to generate the above:

I totally understand that these data structures are meant to be unordered. However, it seems that some sorting is occurring in the jinja2 tojson filter. Perhaps I am misunderstanding what is happening here...how can I preserve the initial ordering while also making this data available to js? Django has a filter that allowed this {{ json_output | json_script:"api_out"}} but I can't seem to replicate with Flask/FastAPI.
Just noticed the same problem in Jinja2. To change this you have to add a new key to the Environment:
env.policies['json.dumps_kwargs'] = {'sort_keys': False}
All credits to Alexander Chzhen, who posted the solution they found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With