在Flask模板中编码JSON

the*_*ses 9 python json flask

我想使用json.dumps()漂亮打印 JSON我的应用程序中.目前,我的模板设置如下:

<table>
{% for test in list_of_decoded_json %}
    <tr>
        <td><pre>{{ test|safe }}</pre></td>
    </tr>
{% endfor %}
</table>
Run Code Online (Sandbox Code Playgroud)

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

知道jinja2不支持json.dumps()模板中的功能,我怎么能得到我想要的漂亮的印刷布局?

Iva*_*hko 14

您可以创建自己的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
Run Code Online (Sandbox Code Playgroud)

然后在模板中使用它:

<table>
{% for test in list_of_decoded_json %}
    <tr>
        <td><pre>{{ test|tojson_pretty|safe }}</pre></td>
    </tr>
{% endfor %}
</table>
Run Code Online (Sandbox Code Playgroud)


小智 2

您可以像这样使用 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))
Run Code Online (Sandbox Code Playgroud)

然后在模板中格式化它,如下所示:

{% if test %}
   <pre>{{ test }}</pre>
{% endif %}
Run Code Online (Sandbox Code Playgroud)

如果这符合您的期望,您可以通过更改 indent 属性的值来控制缩进。