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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With