javascript JSON 解析 - 名称内的单引号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8012721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:59:22  来源:igfitidea点击:

JSON parse - single quote inside name

javascriptjson

提问by Wojciech Bednarski

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. From the same reason I cannot replace surrounding quotes by double and escape double quotes inside JSON string.

我无法在 JSON 字符串中转义单引号,因为这样 JSON 字符串就会无效。出于同样的原因,我不能用双引号替换周围的引号并在 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?

如何以更清晰的方式解决这个问题?

回答by Moishe Lettvin

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.

创建一个 type 的脚本元素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"\'")