JSON encoding inside Flask template

I want to use json.dumps()for pretty print JSON inside my application. My template is currently configured as follows:

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

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

Knowing that jinja2 does not support the function json.dumps()in the template, how can I get the pretty printed layout that I want?

+4
source share
2 answers

You can create your own filter to_pretty_json. First of all, you should wrap json.dumps()in a new function, and then register it as a 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>
+5

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 %}

, , indent.

+1

Source: https://habr.com/ru/post/1623183/


All Articles