简体   繁体   中英

Are double quotes supported in a JSON string?

When I escape double quotes via \\" in a JSON string the parser fails. However, when I use JSON.stringify it is capable of properly escaping the string somehow.

I suspect that I'm not escaping the double quotes properly. Look to the code for more detail.

 var data = { "singleQuoteHtml": "<span class='qwer'>content</span>", "doubleQuoteHtml": "<span class=\\"qwer\\">content</span>", "singleQuote": "'hi'", "doubleQuote": "\\"hi\\"" }; var dataString = '{"singleQuoteHtml": "<span class=\\'qwer\\'>content</span>",' + '"doubleQuoteHtml": "<span class=\\"qwer\\">content</span>",' + '"singleQuote": "\\'hi\\'",' + '"doubleQuote": "\\"hi\\"' + '}'; function Parse() { //Stringify is capable of creating single quotes and double quotes console.log(JSON.parse(JSON.stringify(data))); //When I escape double quotes myself the parser fails //Uncomment to see failure //console.log(JSON.parse(dataString)); } 
 <button onclick="Parse();">Parse JSON </button> 

The string literal '... "\\"hi\\""...' evaluates to ""hi"" , without backslashes.

The backslashes are swallowed as escape sequences by the string literal.

You need to escape your backslashes as \\\\ to put actual backslashes in your string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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