[英]Encoding JSON inside Flask template
我想使用json.dumps()
在我的应用程序中打印 JSON。 目前,我的模板设置如下:
<table>
{% for test in list_of_decoded_json %}
<tr>
<td><pre>{{ test|safe }}</pre></td>
</tr>
{% endfor %}
</table>
test
是解码的JSON字符串。 但是,此实现仅在一行中打印JSON字符串。
知道jinja2不支持模板中的json.dumps()
函数,我怎样才能得到我想要的漂亮的打印布局?
您可以创建自己的to_pretty_json
过滤器。 首先,你必须将json.dumps()
包装成一个新函数,然后将其注册为jinja过滤器 :
import json
def to_pretty_json(value):
return json.dumps(value, sort_keys=True,
indent=4, separators=(',', ': '))
app.jinja_env.filters['tojson_pretty'] = to_pretty_json
然后在模板中使用它:
<table>
{% for test in list_of_decoded_json %}
<tr>
<td><pre>{{ test|tojson_pretty|safe }}</pre></td>
</tr>
{% endfor %}
</table>
您可以像这样使用json.dumps:
@app.route('/')
def home():
return render_template(
'index.html',
title='Home Page',
result=json.dumps({"a":[{"o":1},{"o":2}]}, sort_keys = False, indent = 2))
并在模板中格式化它,如下所示:
{% if test %}
<pre>{{ test }}</pre>
{% endif %}
如果这符合您的期望,您可以通过更改缩进属性的值来控制缩进。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.