繁体   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