Encoding JSON inside Flask template

2020-06-12 05:58发布

问题:

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?

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

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>


回答2:

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.