Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does jinja2 filter "tojson" sort keys?

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:

enter image description here

Code used to generate the above:

enter image description here

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.

like image 263
jclark754 Avatar asked Nov 16 '25 19:11

jclark754


1 Answers

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.

like image 174
Hannes Avatar answered Nov 18 '25 11:11

Hannes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!