如何使用 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/