简体   繁体   English

从服务器端Python将JSON对象获取到客户端Django模板中

[英]Get JSON object from server-side Python into client-side Django template

Server-side, in Python, I'm returning a JSON object that looks like this: 在服务器端,在Python中,我将返回一个如下所示的JSON对象:

 contactAddr = {'name' : name, …}
 contactAddrJSON = json.dumps(contactAddr)

Client side, I'm using Django's template engine to dump that string into a javascript variable, and turning that into an object like this: 客户端,我正在使用Django的模板引擎将该字符串转储到javascript变量中,并将其转换为这样的对象:

 var _myAddressObj = '{{ contactAddrJSON|safe}}';
 var adrObj = $.parseJSON(_myAddressObj);

This worked fine, until I got something where name had a single-quote in it. 这很好,直到我得到名称中包含单引号的内容为止。 I've spent the past couple of hours trying to figure out all these levels of string escapes to get the damn object into Javascript, but to no avail. 我花了过去两个小时的时间来弄清楚所有这些级别的字符串转义,以使该死的对象进入Javascript,但无济于事。 I just need it to be robust to single and double quotes. 我只需要它对单引号和双引号具有鲁棒性。 Can someone enlighten me? 有人可以启发我吗? My brain is smoking. 我的大脑在抽烟。

You can skip the parsing process. 您可以跳过分析过程。 Most JSON data is actually syntactically valid JavaScript, so you can put it directly into the source: 大多数JSON数据实际上是语法上有效的JavaScript,因此您可以将其直接放入源中:

var adrObj = {{ contactAddrJSON|safe}};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM