簡體   English   中英

在 Javascript flask 模板中處理 Python 字典時遇到問題

[英]Having Issues with handling Python dictionaries in Javascript flask templates

因此,我正在使用 flask 構建一個 web 應用程序,該應用程序可以跟蹤多輛車輛並提供更新。 python 腳本有助於收集所有數據並將它們放入字典中。

I am sending this dictionary over to the index.html with the javascript code within the HTML that initializes a map and places markers based on the coordinates received from python.

我遇到的問題是這本字典沒有在 js 中正確解析,因此我沒有得到任何數據。

現在我有 {{truck_dict}} 占位符來保存 html 中 python 的字典 object。

PS。 我不是最擅長 JS 所以不要評判 XD

#Python Code
return render_template('pages/index.html', trucks = truck.driver_locator(truck.locations()))
#Even when I jsonify/json.dump the variable in the trucks object, nothing happens
#JS Code
var truck_dict = {{trucks | tojson}}
var i;
for (var key in truck_dict){
var value = truck_dict[key];
var geojson = {
      type: 'FeatureCollection',
      features: [{
            type: 'Feature',
            geometry: {
            type: 'Point',
            coordinates: value
         },
            properties: {
                  title: 'Mapbox',
                  description: '1303'
                  }
               }]
         };

python 生成的字典的樣本 OUTPUT

{'1301': [43.1220307, -78.9352247], '1302': [42.3107737, -77.2519131], '1304': [40.3809016, -74.5665863], '1305': [40.2453049, -74.5707928], '1303': [39.6435448, -75.9325289]}

這是 output:

var truck_dict = {'1301': [43.1220307, -78.9352247], '1302': [42.3107737, -77.2519131], '1304': [40.3809016, -74.5665863], '1305': [40.2453049, -74.5707928], '1303': [39.6435448, -75.9325289]};

for (var i in truck_dict) {
  console.log(i, truck_dict[i]);
}

output:

1301 [43.1220307, -78.9352247]
1302 [42.3107737, -77.2519131]
1303 [39.6435448, -75.9325289]
1304 [40.3809016, -74.5665863]
1305 [40.2453049, -74.5707928]

因此,您需要記錄 truck_dict,例如:

var truck_dict = {{trucks | tojson}};

console.log(trucks);
console.log(truck_dict);

您正在嘗試索引字典truck_dict[I]在這里不起作用,因為您的索引不是數字(無論如何在 js 中都不可能)。

您需要使用其鍵(例如truck_dict['1301']truck_dict.1301 )而不是索引來訪問字典元素。 如果要遍歷每個鍵(您可以使用它來引用映射到該鍵的值),請使用:

for(var key in truck_dict) {
  var value = truck_dict[key];
  // do what you need with value and key here
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM