JSON解析-名称内的单引号 [英] JSON parse - single quote inside name
问题描述
在Django模板中,我已打印出如下数据:
In Django template I have printed out data like this:
P.place = '{{place.json|safe}}';
然后在JavaScript文件中像这样对它进行解析:
Then in JavaScript file I'm paring it like that:
place = JSON.parse(P.place);
一切都适合这样的数据:
Everything is fine for data like that:
{"category": "Cars", "name": "Z"}
因为字符串看起来像这样:
Because string looks like that:
P.place = '{"category": "Cars", "name": "Z"}'
因此,我可以使用JSON.parse方法witch接受字符串作为输入来解析它.
So, I can parse it using JSON.parse method witch accept strings as input.
问题是当我得到这样的数据时:
Problem is when I get data like that:
{"category": "Cars", "name": "Wojtek's Z"}
因为JSON解析器的输入字符串如下所示:
Because than input string for JSON parser looks like that:
'{"category": "Cars", "name": "Wojtek'
我无法在JSON字符串中转义单引号,因为这样JSON字符串将变为无效.基于相同的原因,我无法用双引号替换周围的引号,并且无法在JSON字符串中转义双引号.
I cannot escape single quote inside JSON string, because then JSON string become invalid. From the same reason I cannot replace surrounding quotes by double and escape double quotes inside JSON string.
我的解决方案如下:
在HTML模板中:
P.place = {{place.json|safe}};
然后用JavaScript
Then in JavaScript
var place = JSON.stringify(P.place);
place = JSON.parse(place);
它可以工作,但不是IMHO的最佳解决方案.
It works, but it is not optimal solution IMHO.
如何用更切肉的方式解决这个问题?
How to solve this problem in more cleaver way?
推荐答案
我可以想到两种可能性:
I can think of two possibilities:
创建类型为application/json
的脚本元素,将模板数据注入其中,然后读取其数据,例如.
Create a script element of type application/json
, inject your template data into it, then read its data, eg.
<script id="place-json" type="application/json">
{{place.json|safe}}
</script>
<script type="application/javascript">
P.place = $('#place-json').text();
</script>
或者,在注入字符串之前手动转义单引号,例如.
Or, manually escape the single quotes before injecting the string, eg.
simplejson.dumps(yourdata).replace("'", r"\'")
这篇关于JSON解析-名称内的单引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!