简体   繁体   中英

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:

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

You can use json.dumps like so:

@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))

and just format it in the template like so:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM