python - Django:使用 Javascript 在我的模板中解析 JSON

标签 python json django django-templates

我认为这是:

string_location = myaddress2
    geodata = []
    for place, (lat, lng) in g.geocode(string_location,exactly_one=False):
        geodata.append((place, (lat, lng)))

    geodata_results = len(geodata)

    data = {"geodata": geodata, "geodata_results":geodata_results }
    return render_to_response("business/business_view.html",
                              data, context_instance=RequestContext(request))

我将如何“处理”/将 geodata 转换为 JSON 并将其传递给我的模板,以便我可以像数组一样“循环”它?

我认为我可以这样做是对的吗?如果没有,请提出更好的解决方案。

谢谢!

更新

var geodata = "[["M. L. Quezon Street<br/>Mandaue City, Philippines", [10.351381999999999, 123.923535]], ["Talamban<br/>Cebu City, Philippines", [10.353527, 123.91352500000001]]]"; 

我认为 JSON 没有转义?如何转义 json 字符串中的特殊字符? 我不断收到换行错误。

对于 PHP,我会用 json_encode() 来解决这个问题。喜欢这篇文章:Pass a PHP string to a JavaScript variable (and escape newlines)但是我如何在 Python/Django 中做到这一点?

最佳答案

您可以使用内置的 json 模块:

>>> import json
>>> geodata = [ ( "Here", (1003,3004) ), ("There", (1.2,1.3)) ]
>>> json.dumps(geodata)
'[["Here", [1003, 3004]], ["There", [1.2, 1.3]]]'

然后您可以简单地将生成的字符串嵌入到 javascript 脚本中:

<script type='text/javascript'>
var geodata = {{ geodata|safe }};
</script>

关于python - Django:使用 Javascript 在我的模板中解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3345076/

相关文章:

python - 你如何遍历一棵树?

json - 如何使用 groovy 解析 json

javascript - 如果 JSON 字符串有\n,则 JSON.parse 失败

django - 如何在 django-crispy-forms 中将表单字段分布在两列布局上?

python - 如何在 Django 中改进这个 "register" View ?

django - mark_safe 不起作用/仍在 simple_tag 中转义

python - 在测试中使用 url_for

python - 使用另一个时间戳数据帧来过滤 pandas 上的时间戳数据帧

python - 如何使用 web.py 显示图像

php - 使用 jQuery 通过 Ajax 返回 JSON