getting json dictionary values, though python and jinja getting json dictionary values, though python and jinja json json

getting json dictionary values, though python and jinja


You should better decode JSON to python dictionary in view function and pass it into jinja:

import json@app.route("/something")def something():    with open('myfile.json', 'r') as f:        json_data = json.loads(f.read())    return render_template("something.html", json_data=json_data)

something.html:

<dl>{% for key, value in json_data.iteritems() %}    <dt>{{ key|e }}</dt>    <dd>{{ value|e }}</dd>{% endfor %}</dl>


If your goal is to print a pretty json string then it might be better to prepare the actual string before passing it to jinja.

In the view you can do this:

import json@app.route("/something")def something():    with open('myfile.json', 'r') as f:        json_data = json.loads(f.read())        formatted_json = json.dumps(            json_data,            sort_keys=True,            indent=4,            separators=(',', ': '))    return render_template("something.html", json=formatted_json)

And in your something.html you simply print that already formatted variable:

{{ json }}

You can read more about the json string formatting in the documentation section about "pretty printing"