Reputation: 289
I have a dictionary in json that Im passing though into jinja using python. The page is not working not sure if this is the correct syntax
{% with open(jsonobject, 'r') as f
json_data = json.load(f)
for a, (b,c) in json_data.items() %}
--------------EDIT----------- This is a large dictionary within the json object being passed int which looks something like this
{"Dogs": [["spot"], 1], "Cats": [["whiskers"], 1], "fish": [["bubbles", "lefty", "tank", "goldie"], 4], "elephant": [["tiny", "spring"], 2], "zebra": [[], 1], "gazelle": [["red", "blue", "green", "yellow", "gold", "silver"], 6]}
Upvotes: 3
Views: 11190
Reputation: 3819
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"
Upvotes: 1
Reputation: 1267
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>
Upvotes: 2