[英]Trouble accessing data from a JSON object that was originally a Python dictionary in Flask
新手來了我正在為介紹 CS class 使用公寓大樓和公寓單元的數據庫,並嘗試使用 flask 構建 web 應用程序。
在 application.py 中,我有這樣的東西:
locationdict =
{
"Complex A": [1, 2, 3],
"Complex B": [4, 5, 6]
}
JSONlocationdict = json.dumps(locationdict, sort_keys=True)
return render_template("start.html", JSONlocationdict=JSONlocationdict)
但是,當我嘗試從 JavaScript 中的字典訪問該數據時,似乎沒有任何效果。 HTML 頁面大致如下所示:
<button onclick = "getUnits(this)" id="Complex A"> Complex A </button>
<script>
function getUnits(arg) {
var locationName = arg.getAttribute("id");
var JSONlocationdict = "{{ JSONlocationdict }}";
console.log(JSONlocationdict)
// In the console, this is what you see:
// {"Complex A": [1,2,3], "Complex B", [4,5,6]}
var obj = JSON.parse(JSONlocationdict);
console.log(obj); // this returns the error
// Then you see this in the console:
// Uncaught SyntaxError: Unexpected token & in JSON at position 1
// at JSON.parse (<anonymous>)
// at getUnits (start:88)
// at HTMLButtonElement.onclick (start:119)
var units = obj["Complex A"];
console.log(units);
// That last request to log to the console does nothing so far.
}
</script>
我嘗試使用不同的方法將原始字典轉換為 JSON,如 jsonify 和 json.loads() 而不是 dumps()。 我已經在 stackoverflow 上瀏覽了大量關於 SyntaxError: Unexpected token 的條目,但我似乎無法得到任何工作。 有任何想法嗎??
唯一似乎可靠工作的是有兩個單獨的頁面 - 用戶可以從公寓大樓列表中 select 的第一頁,然后將它們發送到第二頁,然后他們可以選擇單元。
不過,如果他們可以單擊公寓大樓的按鈕,然后在同一頁面上動態生成該大樓的可用單元列表,那就太好了。
Flask 方法 render_template 將您的 JSON 轉換為字符串,您可以通過記錄 JSONlocationdict 看到。 由於它將字符串呈現為 HTML,因此它會轉義雙引號字符,這就是您的 JavaScript 解析時遇到的問題。
要解決此問題,您需要先取消轉義 JSONlocationdict,然后再將其傳遞給 JSON.parse。 有很多方法可以做到這一點,如果你想在瀏覽器中這樣做, 這里接受的答案應該適用於你的情況。
function htmlDecode(input){ var e = document.createElement('textarea'); e.innerHTML = input; // handle case of empty input return e.childNodes.length === 0? "": e.childNodes[0].nodeValue; } t = '{"Complex A": [1,2,3], "Complex B": [4,5,6]}' x = htmlDecode(t) console.log(JSON.parse(x))
注意:在上面的代碼段中,我必須編輯您問題中的 console.log 響應,以便在“Complex B”之后而不是那里的逗號。
如果結果實際上是您的問題,那么 JSON 沒有被 Flask 正確格式化,盡管您的 Flask 代碼看起來正確。
還有其他方法可以使用 AJAX 和另一個 Flask URL 返回 jsonify 響應來完成此任務。 還有一些模板過濾器(如 |safe)可以做到這一點,但取決於您使用的模板庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.