[英]JSON parse - single quote inside name
In Django template I have printed out data like this: 在Django模板中,我打印出如下数据:
P.place = '{{place.json|safe}}';
Then in JavaScript file I'm paring it like that: 然后在JavaScript文件中,我正在削减它:
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"}'
So, I can parse it using JSON.parse method witch accept strings as input. 所以,我可以使用JSON.parse方法解析它,接受字符串作为输入。
Problem is when I get data like that: 问题是我得到这样的数据:
{"category": "Cars", "name": "Wojtek's Z"}
Because than input string for JSON parser looks like that: 因为JSON解析器的输入字符串看起来像这样:
'{"category": "Cars", "name": "Wojtek'
I cannot escape single quote inside JSON string, because then JSON string become invalid. 我无法在JSON字符串中转义单引号,因为那时JSON字符串变得无效。 From the same reason I cannot replace surrounding quotes by double and escape double quotes inside JSON string. 出于同样的原因,我无法用双重替换周围的引号,并在JSON字符串中转义双引号。
My solution looks like that: 我的解决方案如下:
In HTML template: 在HTML模板中:
P.place = {{place.json|safe}};
Then in JavaScript 然后在JavaScript中
var place = JSON.stringify(P.place);
place = JSON.parse(place);
It works, but it is not optimal solution IMHO. 它有效,但它不是最佳解决方案恕我直言。
How to solve this problem in more cleaver way? 如何以更多的方式解决这个问题?
I can think of two possibilities: 我可以想到两种可能性:
Create a script element of type application/json
, inject your template data into it, then read its data, eg. 创建一个application/json
类型的脚本元素,将模板数据注入其中,然后读取其数据,例如。
<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"\'")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.