3

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]}
jumpman8947
  • 249
  • 3
  • 6
  • 13
  • can you provide the error you're getting. at the very least, you're missing a color after f. and the for loop syntax is incorrect – Garrett R Jan 22 '16 at 22:33

2 Answers2

2

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>
dizballanze
  • 1,267
  • 8
  • 18
1

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"

replay
  • 3,569
  • 3
  • 21
  • 30