Skip to content Skip to sidebar Skip to footer

Encoding Json Inside Flask Template

I want to use json.dumps() to pretty print JSON inside my app. Currently, my template is set up like this: {% for test in list_of_decoded_json %}

Solution 1:

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

defto_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>

Solution 2:

You can use json.dumps like so:

@app.route('/')defhome():
    return render_template(
    'index.html',
     title='Home Page',
     result=json.dumps({"a":[{"o":1},{"o":2}]}, sort_keys = False, indent = 2))

and just format it in the template like so:

{% iftest %}
   <pre>{{ test }}</pre>
{% endif %}

If this fits to your expectations, you can control the indention by changing the value of the indent property.

Post a Comment for "Encoding Json Inside Flask Template"