简体   繁体   English

复制和粘贴带转义引号的字符串对象时出现JSON.parse异常

[英]JSON.parse exception when copy & pasting stringified objects with escaped quotes

I have to stringify some JS objects to save the text somewhere and I'd like to be able to copy the saved text manually afterwards and pass it via the console to a function which then parses the text to do something with the original object. 我必须对一些JS对象进行字符串化处理才能将文本保存在某个地方,然后我希望能够手动复制保存的文本,然后通过控制台将其传递给一个函数,该函数可以对文本进行解析以对原始对象进行处理。

Unfortunately parsing pasted text seems to have problems with escaped double quotes since parsing always fails. 不幸的是,因为粘贴总是失败,所以解析粘贴的文本似乎存在转义双引号的问题。

I have created a small snippet which illustrates my problem: 我创建了一个小片段来说明我的问题:

http://jsfiddle.net/wgwLcgz6/1/ http://jsfiddle.net/wgwLcgz6/1/

var jsonStr = JSON.stringify({ arg1: 'some string "with quotes"' });

$('#out1').html(jsonStr); // {"arg1":"some string \"with quotes\""}
JSON.parse(jsonStr); // Works just fine
try {
    // Copied the ouput of JSON.stringify manually and pasted it directly into
    // the parse function...
    JSON.parse('{"arg1":"some string \"with quotes\""}');

    // We never get here since an exception is thrown
    $('#out2').html('Parsed successfully');
} catch (ex) {
    // SyntaxError: Unexpected token w
    $('#out2').html(ex.toString());
}

I think I do understand why this is happening even though I can't explain it properly but I don't have any idea on how to circumvent this and would really appreciate some help and maybe deeper explanation. 我想我确实理解了为什么会发生这种情况,即使我无法正确解释,但我对如何避免这种情况一无所知,并且会非常感谢您的帮助和更深入的解释。

One more thing: If I paste the stringified object {"arg1":"some string \\"with quotes\\""} into an online json parser like http://jsonlint.com/ it parses it just fine which I guess is because they use there own parser instead of the browsers built in ones... 还有一件事:如果我将字符串化的对象{"arg1":"some string \\"with quotes\\""}粘贴到在线json解析器中,例如http://jsonlint.com/,它将解析得很好,我想这是因为他们使用自己的解析器,而不是内置的浏览器...

You need to escape quotes and backslashes. 您需要转义引号和反斜杠。 Since you're using single quotes around a string with double quotes, you just have to escape the backslashes: 由于您在带双引号的字符串周围使用单引号,因此只需要转义反斜杠即可:

JSON.parse('{"arg1":"some string \\"with quotes\\""}');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM