在Flask模板中编码JSON [英] Encoding JSON inside Flask template

查看:300
本文介绍了在Flask模板中编码JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用json.dumps()在我的应用程序中精美打印 JSON. 目前,我的模板是这样设置的:

I want to use json.dumps() to pretty print JSON inside my app. Currently, my template is set up like this:

<table>
{% for test in list_of_decoded_json %}
    <tr>
        <td><pre>{{ test|safe }}</pre></td>
    </tr>
{% endfor %}
</table>

其中test是解码的JSON字符串.但是,此实现仅将JSON字符串打印在一行中.

Where test is the decoded JSON string. However, this implementation only prints the JSON strings in one line.

知道jinja2不支持模板中的json.dumps()函数,如何获得所需的漂亮印刷版图?

Knowing that jinja2 doesn't support the json.dumps() function in-template, how can I get the pretty printed layout that I want?

推荐答案

您可以创建自己的to_pretty_json过滤器.首先,您必须将json.dumps()包装到一个新函数中,然后将其注册为进阶过滤器:

You can create your own to_pretty_json filter. First of all, you have to wrap json.dumps() into a new function and then register it as jinja filter:

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>

这篇关于在Flask模板中编码JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆