我想在我的页面上列出嵌套 JSON 的内容。要实现此目的,需要对 Awesome.html 进行哪些更改?
是否无法在不指定特定子类别的情况下一次性列出所有内容?
更具体地说,awesome.html 中的这部分代码不起作用:
{% for each_category in content -%}
{{ each_category }} {{ content[each_category].each_category.items() }}
{% endfor %}
我尝试在 for 循环内使用第二个 for,但根本不起作用:
{% for each_category in content -%}
{{ each_category }}
{% for each_subcategory in each_category -%}
{{ each_subcategory }} {{ content[each_subcategory].port }}
{% endfor %}
{% endfor %}
此代码有效,但它仅列出端口,而我想要所有内容,而不仅仅是端口:
{% for each_category in content -%}
{{ each_category }} {{ content[each_category].port }}
{% endfor %}
额外信息
configs/env.json 的示例内容:
{
"env" : {
"db" : {
"postgres_db_useradmin" : "devadmin",
"postgres_db_useradmin_pw" : "sdfkjsnbdfjkgb",
"port" : "2134",
"app" : "sdfszdg"
},
"ssh" : {
"ssh_user" : "ubuntu",
"ssh_server" : "website.com",
"port" : "22"
},
"app" : {
"ht_protocol" : "http",
"port" : "8080"
}
}
}
在 app.py 中加载 JSON,片段
with open('configs/env.json', 'r') as json_file:
env_dict = json.load(json_file)
content = env_dict['env'] # removing the top env category, because it is the only one
使用jinja语法的awesome.html内容需要更改:
{% extends 'index.html' %}
{% block content %}
<h1>Awesome page</h1>
{% for each_category in content -%}
{{ each_category }} {{ content[each_category].each_category.items() }}
{% endfor %}
{% endblock %}
我发现了类似的问题,但无法根据我的情况调整解决方案:
感谢您的帮助!
最佳答案
我做到了!
解决方案是使用嵌套的 for 循环,而不是使用点符号,而是使用 [ ] 来引用值。
这里我将content
重命名为all_content
。
each_category
是 db、ssh、app,作为字典的键。
all_content[each_category]
指 db、ssh、app 内的容器,即这些键的值。
each_subcategory
代表 postgres_db_useradmin
、postgres_db_useradmin_pw
等。
all_content[each_category][each_subcategory]
是键 postgres_db_useradmin
、postgres_db_useradmin_pw
等的值,这意味着 devadmin
、sdfkjsnbdfjkgb
等。
{% for each_category in all_content -%}
{{ each_category }}
{% for each_subcategory in all_content[each_category] %}
{{ each_subcategory }} {{ all_content[each_category][each_subcategory] }}
{% endfor %}
{% endfor %}
关于python - Jinja 使用 for 列出嵌套 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62593064/