Jinja2 - 如何循环一个 json 列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32085758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:01:52  来源:igfitidea点击:

Jinja2 - How to loop a json list?

jsonpython-2.7jinja2

提问by laukok

How can I loop a json list with jinja2?

如何使用 jinja2 循环 json 列表?

I have this json list,

我有这个json列表,

[
    {
        "first_name": "John",
        "last_name": "Smith",
        "user_id": 4,
        "address": null
    },
    {
        "first_name": "Jane",
        "last_name": "Heart",
        "user_id": 5,
        "address": null
    },
    {
        "first_name": "Dom",
        "last_name": "Robinsons",
        "user_id": 6,
        "address": null
    },
    {
        "first_name": "Pete",
        "last_name": "Hand",
        "user_id": 7,
        "address": null
    }
]

page.html,

页面.html,

<table>
   {% for user in users %}
   <tr><td>{{ user.first_name }}</td></tr>
   {% endfor %}
</table>

Result,

结果,

<table>

   <tr><td></td></tr>

   <tr><td></td></tr>

   <tr><td></td></tr>

   <tr><td></td></tr>
   ...

Any ideas?

有任何想法吗?

回答by hiro protagonist

your json list contains dictionaries; you need to access the dictionary elements differently than you would class members; try:

您的 json 列表包含字典;您需要以不同于类成员的方式访问字典元素;尝试:

<tr><td>{{ user['first_name'] }}</td></tr>

this works for me (python 3.4 and python 2.7)

这对我有用(python 3.4 和 python 2.7)

import json
from jinja2 import Template

json_str = '''[{"first_name": "John", "last_name": "Smith", "user_id": 4, 
    "address": null}, {"first_name": "Jane", "last_name": "Heart",
    "user_id": 5, "address": null}, {"first_name": "Dom",
    "last_name": "Robinsons", "user_id": 6, "address": null},
    {"first_name": "Pete", "last_name": "Hand", "user_id": 7,
    "address": null}]'''

users = json.loads(json_str)

tmpl = Template('''
<table>
   {% for user in users %}
   <tr><td>{{ user['first_name'] }}</td></tr>
   {% endfor %}
</table>
''')

print(tmpl.render(users = users))

output:

输出:

<table>

   <tr><td>John</td></tr>

   <tr><td>Jane</td></tr>

   <tr><td>Dom</td></tr>

   <tr><td>Pete</td></tr>

</table>

回答by Majid Zandi

simple json iteration in jinja2

jinja2中的简单json迭代

<table>
   <tr>
       {% for key in users[0] %}
       <th>{{ key }}</th>
       {% endfor %}
   </tr>

   {% for user in users %}
   <tr>
       {% for key in user %}
       <td>{{ user[key] }}</td>
       {% endfor %}
   </tr>
   {% endfor %}
</table>