Jinja2-如何循环json列表? [英] Jinja2 - How to loop a json list?
本文介绍了Jinja2-如何循环json列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用jinja2循环json列表?
How can I loop a json list with jinja2?
我有这个json列表,
I have this json list,
[
{
"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,
page.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列表中包含字典;您需要以不同于成员的方式访问字典元素;尝试:
your json list contains dictionaries; you need to access the dictionary elements differently than you would class members; try:
<tr><td>{{ user['first_name'] }}</td></tr>
这对我有用(python 3.4和python 2.7)
this works for me (python 3.4 and 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>
这篇关于Jinja2-如何循环json列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文