2016-10-17 39 views
0

我坐在基於Flask的web應用程序上。理論上我想從磁盤加載一個JSON文件,並將它提供給網站上的JavaScript。JSON編碼Flask to Javascript

def getData(): 
    check_for_update() 
    with open(LOCAL_file,"rb") as myfile: 
     data = json.load(myfile) 
    udate = data["today"] 
    return (udate, data) 

然後我把它發送到頁面

return render_template('./index2.html', udate = thisdata[0], data = json.dumps(thisdata[1])) 

現在在頁面上我只是嘗試

<script> 
var myjson = JSON.parse({{data}}) 
</script> 

,然後導致這樣的事情

enter image description here

這不能不被解析。當我複製並粘貼它時,它工作正常,並且python也不會抱怨。

+0

這裏有兩個不同的問題和正在運行到他們依次,這使得它很難把它作爲一個副本來關閉。它們是:1. [Mustache JS模板 - 如何在腳本標記字符串中嵌入變量?](http://stackoverflow.com/questions/9051281/mustache-js-templating-how-do-i-embed- a-variable-in-a-script-tag-string) 2. [我不斷收到「Uncaught SyntaxError:Unexpected token o」](http://stackoverflow.com/questions/8081701/i-keep-getting-uncaught -syntaxerror-unexpected-token-o) – Quentin

+0

@Quentin:這不是一個鬍鬚模板。默認的Flask模板enginge Jinja2也使用'{{..}}'佔位符。而OP只是忘了禁用標準的HTML轉義。 –

+0

在HTML中生成的輸出仍然是* text *。如果您將其作爲文本粘貼而不是使用圖像,則無法複製或搜索圖像內容。 –

回答

2

dataHTML轉義,因爲默認情況下,Jinja2會將所有內容都轉義爲可安全嵌入HTML頁面。

最好不要在視圖中編碼爲JSON,而是在模板中執行此操作,並使用Flask tojsonsafe過濾器。

所以在thisdata[1]未編碼的視圖通:

return render_template(
    './index2.html', udate=thisdata[0], data=thisdata[1]) 

,並在視圖:

<script> 
var myjson = {{ data|tojson|safe }}); 
</script> 

tojson產生JSON數據,這也是HTML安全(儘管有"報價,所以它不適合嵌入到HTML標記屬性中),並且safe過濾器可用於關閉HTML編碼。這裏不需要使用JSON.parse(),由tojson產生的結果JSON是一個嚴格的JavaScript子集。

JSON Support section API文檔中:

The htmlsafe_dumps() function of this json module is also available as filter called |tojson in Jinja2. Note that inside script tags no escaping must take place, so make sure to disable escaping with |safe if you intend to use it inside script tags[.]

和瓶模板文件的Standard Filters section

tojson()
This function converts the given object into JSON representation. This is for example very helpful if you try to generate JavaScript on the fly.