P.Brian.Mackey
P.Brian.Mackey

Reputation: 44275

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>

Upvotes: 0

Views: 1296

Answers (1)

SLaks
SLaks

Reputation: 887453

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.

Upvotes: 4

Related Questions