Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding JSON inside Flask template

Tags:

python

json

flask

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>

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

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

like image 959
thevises Avatar asked Jan 07 '16 01:01

thevises


1 Answers

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

And then use it in the template:

<table>
{% for test in list_of_decoded_json %}
    <tr>
        <td><pre>{{ test|tojson_pretty|safe }}</pre></td>
    </tr>
{% endfor %}
</table>
like image 192
Ivan Velichko Avatar answered Sep 19 '22 11:09

Ivan Velichko