python - Jinja 使用 for 列出嵌套 JSON

标签 python json dictionary flask jinja2

我想在我的页面上列出嵌套 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 %}

我发现了类似的问题,但无法根据我的情况调整解决方案:

Jinja parsing a nested JSON

感谢您的帮助!

最佳答案

我做到了!

解决方案是使用嵌套的 for 循环,而不是使用点符号,而是使用 [ ] 来引用值。

这里我将content重命名为all_content

each_category 是 db、ssh、app,作为字典的键。

all_content[each_category] 指 db、ssh、app 内的容器,即这些键的值。

each_subcategory 代表 postgres_db_useradminpostgres_db_useradmin_pw 等。

all_content[each_category][each_subcategory] 是键 postgres_db_useradminpostgres_db_useradmin_pw 等的值,这意味着 devadminsdfkjsnbdfjkgb 等。

    {% 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/

相关文章:

Python zipfile 在写入时挂起

python - 在 Pool.map 中使用生成器作为可迭代是否合理

java - 使用改造将 json 解析为 POJO

python - Python 中的 CSV 到 dict

python Bokeh : get image from webcam and show it in dashboard

python - 对 pandas 数据框的列执行累积求和,忽略 NAN

javascript - AngularJS 使用 $HTTP.JSONP 解析 json 时出现问题

json - 如何使用 Excel Power Query 仅从 Azure Blob 存储查询值?

swift - 初学者 swift : Converting string if letter in dictionary

python - 使用正则表达式分组将字符串转换为字典