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

标签 json python-2.7 jinja2

如何使用 jinja2 循环 json 列表?

我有这个 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
    }
]

页面.html,

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

结果,

<table>

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

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

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

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

有什么想法吗?

最佳答案

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

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

这对我有用(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))

输出:

<table>

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

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

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

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

</table>

关于json - Jinja2 - 如何循环 json 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32085758/

相关文章:

python - 在 Python 中更新 JSON 文件

python - 如何在 jinja2 中设置可选参数

python - 使用 Jinja2 渲染字典或字符串

Ansible修改列表元素

java - 递归方法返回存储为 JSON 文件的不同对象

javascript - 在 jQuery 中使用 JSON 变量来显示更多 JSON 变量

python - 如何从 Azure ML 中的 python 脚本获取 Web 服务的输出

Python 记录到标准输出和 StringIO

python-2.7 - Python lightgbm feature_importance() 错误?

python - AWS S3特殊字符编码