Django:使用Javascript在我的模板中解析JSON [英] Django: Parse JSON in my template using Javascript

查看:154
本文介绍了Django:使用Javascript在我的模板中解析JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个看法:

  string_location = myaddress2 
geodata = []
地址,(lat,lng)in g.geocode(string_location,exact_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 ))

我将如何处理/转换地理数据到JSON和将它传递给我的模板,以便我可以像数组一样循环



我是否认为我可以这样做?如果没有,请建议一个更好的解决方案。



谢谢!



更新

  var geodata =[[& quot; ML Quezon Street& lt; br /&菲律宾,[10.351381999999999,123.923535]],[& quot; Talamban& amp; gt; Cebu City,Philippines&,[10.353527,123.91352500000001]]] 

我认为JSON没有被转义?如何避免在json字符串内部的特殊字符?
我不断得到一个换行错误。



对于PHP,我将json_encode()来解决这个问题。像这篇文章:将一个PHP字符串传递给一个JavaScript变量(和转义换行符)但是如何在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]]]'
pre>

然后,您可以直接将生成的字符串嵌入到JavaScript脚本中:

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


I have this in my view:

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))

How would I "handle" / convert geodata into JSON and pass it to my template so that I can "loop" through it like an array?

Am I right to think that I can do it this way? If not, then please suggest on a better solution.

Thanks!

UPDATE

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

I think the JSON is not escaped? How do I escape special characters inside the json string? I keep getting a newline error.

For PHP, I would json_encode() to fix this. Like in this post: Pass a PHP string to a JavaScript variable (and escape newlines) BUT how do I do that in Python/Django?

解决方案

You could use the built-in json module:

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

You can then simply embed the resulting string inside a javascript script:

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

这篇关于Django:使用Javascript在我的模板中解析JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆