Javascript json 值中的单引号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32143704/
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-08-23 07:39:55  来源:igfitidea点击:

Single quotes within json value

javascriptjsonformatting

提问by ezero

Javascript fails to read this json string as it contains a single quote character which it sees as the end of the string.

Javascript 无法读取这个 json 字符串,因为它包含一个单引号字符,它认为是字符串的结尾。

How can I escape the single quote so that it is not seen as the end of the string?

如何转义单引号,使其不被视为字符串的结尾?

var json = '{"1440167924916":{"id":1440167924916,"type":"text","content":"It's a test!"}}';

var parsed = JSON.parse(json);

采纳答案by CodingIntrigue

Use a backslash to escape the character:

使用反斜杠转义字符

var json = '{"1440167924916":{"id":1440167924916,"type":"text","content":"It\'s a test!"}}';
var parsed = JSON.parse(json);

回答by Noble Mushtak

Just escape the single quote with a backslash such as \':

只需使用反斜杠转义单引号,例如\'

var json = '{"1440167924916":{"id":1440167924916,"type":"text","content":"It\'s a test!"}}';

var parsed = JSON.parse(json);

//Output parsed to the document using JSON.stringify so it's human-readable and not just "[object Object]":
document.write(JSON.stringify(parsed));

回答by mechanicals

Escape it with a backslash

用反斜杠转义

var json = '{"1440167924916":{"id":1440167924916,"type":"text","content":"It\'s a test!"}}';

var parsed = JSON.parse(json);