gpt4 book ai didi

python - 为什么 jinja2 过滤 "tojson"排序键?

转载 作者:行者123 更新时间:2023-12-05 03:42:35 26 4
gpt4 key购买 nike

我有一个不灵活的要求来保留 API 输出键的顺序。我将数据作为 python 字典并将其作为上下文传递给 jinja2 模板,如下所示:

....
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,
},
)

如果我只是在模板中使用 {{ json_out }},我发现顺序被保留了下来。如果我使用 {{ json_out | tojson }} (因为我有兴趣将其传递给 javascript),键得到排序。为什么?

看这个例子:

enter image description here

用于生成上述内容的代码:

enter image description here

我完全理解这些数据结构是无序的。但是,似乎在 jinja2 tojson 过滤器中进行了一些排序。也许我误解了这里发生的事情……我怎样才能保留初始顺序,同时让这些数据对 js 可用? Django 有一个过滤器允许这个 {{ json_output | json_script:"api_out"}} 但我似乎无法使用 Flask/FastAPI 进行复制。

最佳答案

刚刚注意到 Jinja2 中的相同问题。要更改此设置,您必须向环境添加一个新 key :

env.policies['json.dumps_kwargs'] = {'sort_keys': False}

感谢 Alexander Chzhen,他发布了他们找到的解决方案 here .

关于python - 为什么 jinja2 过滤 "tojson"排序键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67214142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com