2016-01-22 43 views
1

我有一個json字典,即時通過雖然通過python傳遞到jinja。 頁面不工作不知道這是正確的語法越來越json字典的值,雖然python和jinja

{% with open(jsonobject, 'r') as f 
    json_data = json.load(f) 
    for a, (b,c) in json_data.items() %} 

-------------- -----------編輯這 是JSON對象內的大的字典傳遞INT這看起來是這樣的

{"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]} 
+0

你能提供你得到的錯誤嗎?至少,你在f後缺少一種顏色。 for循環語法不正確 –

+0

for循環語法在python中有效。檢查編輯 – jumpman8947

+0

您不能在Jinja中編寫任意的Python表達式。在視圖中執行復雜的邏輯,並將數據傳遞給模板。 – davidism

回答

2

你應該更好的JSON到Python字典中取景功能解碼,並將其傳遞到神社:

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

如果你的目標是要打印一個漂亮json字符串,那麼它可能會更好它傳遞給jinja之前準備的實際字符串。

在視圖中,你可以這樣做:

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) 

而在你something.html您只需打印已經格式化的變量:

{{ json }} 

你可以閱讀更多關於JSON字符串中的documentation section about "pretty printing"格式