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.

