如果您使用Django或Jinja2,您可能以前遇到过这个问题。 我有一个JSON字符串,如下所示:
{
"data":{
"name":"parent",
"children":[
{
"name":"child_a",
"fav_colors":[
"blue",
"red"
]
},
{
"name":"child_b",
"fav_colors":[
"yellow",
"pink"
]
}
]
}
}
现在我想把这个传递给我的Jinja2模板:
j = json.loads('<the above json here>')
self.render_response('my_template.html', j)
…然后重复如下:
<select>
{% for p in data recursive %}
<option disabled>{{ p.name }}</option>
{% for c in p.children %}
<option value="{{ c.fav_colors|safe }}">{{ c.name }}</option>
{% endfor %}
{% endfor %}
</select>
这就是我遇到问题的地方:除了Jinja2输出c.fav_颜色的unicode编码值之外,其他一切都可以工作。我需要c.fav_颜色作为一个有效的javascript数组,这样我就可以从javascript访问它。如何让Jinja将该值打印为ascii文本,例如:['blue','red']
,而不是[u'blue', u'red']
?
您需要将
fav_colors
列表转换回JSON。可能最简单的方法是使用快速模板过滤器:所以现在你可以
相关问题 更多 >
编程相关推荐