在Django中将字符串转换为Javascript中的词典列表

时间:2018-08-15 00:35:38

标签: javascript python arrays django dictionary

在我的上下文中,有一个名为“ spots”的变量。我有一个脚本可以在文档中打印出来

<script >
    var spotss = "{{ spots }}";
    document.write(spotss)
</script>

上面的代码产生以下结果:

[{u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 2, u'water_type': u'Shallow, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.4026, u'lng': 14.9949, u'spot_name': u'Paestum'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 2, u'water_type': u'Shallow, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.4271, u'lng': 14.9818, u'spot_name': u'Ponte di Ferro'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 9, u'water_type': u'Shallow, Flat, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.343, u'lng': 14.9717, u'spot_name': u'Agropoli'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 21, u'water_type': u'Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.2315, u'lng': 14.9566, u'spot_name': u'Case del Conte'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 26, u'water_type': u'Small wave', u'water_quality': u'Clean', u'lat': 40.1856, u'lng': 15.0239, u'spot_name': u'Acciaroli'}, {u'rider_ability': u'Intermediate, Expert', u'spot_distance': 28, u'water_type': u'Flat, Chop', u'water_quality': u'Crystal clear', u'lat': 40.1732, u'lng': 15.0846, u'spot_name': u'Pioppi'}, {u'rider_ability': u'Beginner, Intermediate, Expert', u'spot_distance': 31, u'water_type': u'Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.1641, u'lng': 15.1423, u'spot_name': u'Marina di Casal Velino'}, {u'rider_ability': u'Expert', u'spot_distance': 35, u'water_type': u'Flat, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.6436, u'lng': 14.6984, u'spot_name': u'Cetara'}, {u'rider_ability': u'Intermediate, Expert', u'spot_distance': 35, u'water_type': u'Shallow, Flat, Chop, Small wave', u'water_quality': u'Clean', u'lat': 40.6775, u'lng': 14.7587, u'spot_name': u'Salerno'}, {u'rider_ability': u'Intermediate, Expert', u'spot_distance': 42, u'water_type': u'Chop, Small wave', u'water_quality': u'Crystal clear', u'lat': 40.6262, u'lng': 14.5883, u'spot_name': u'Spiaggia Duoglie'}]

其中是词典列表,可能是“字符串”。

现在,我需要将该字典列表迭代到同一html上的另一个脚本中,并且我还需要在循环时访问字典值。我该怎么办?

1 个答案:

答案 0 :(得分:2)

使用Django的safe过滤器:

<script >
    var spotss = "{{ spots | safe}}";
    document.write(spotss);
</script>

或者您可能需要:

<script >
    var spotsArray = {{ spots | safe}};
    spotsArray.forEach(function(spot) {
        console.log(spot)
    });
</script>

spotsArray包含对象列表,您可以使用forEach遍历该列表