Single quotes within json value [duplicate]

社会主义新天地 提交于 2019-12-23 07:06:19

问题


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

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);

回答1:


Use a backslash to escape the character:

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



回答2:


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));



回答3:


Escape it with a backslash

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

var parsed = JSON.parse(json);


来源:https://stackoverflow.com/questions/32143704/single-quotes-within-json-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!