K A
K A

Reputation: 197

Escaping double quotation in javascript

I am getting an error when parsing what seems like valid json. The JSON string contains an escaped double-quote character inside of a string.

I've condensed the example to be as simple as possible to reproduce and pasted below. The browser I'm using to test this is Chrome Version 100.0.4896.75.

Can anyone help me understand what I am doing wrong here?

let a = JSON.parse('{"a": "\""}');

Error: { "message": "SyntaxError: JSON.parse: expected ',' or '}' after property value in object at line 1 column 9 of the JSON data", "filename": "https://stacksnippets.net/js", "lineno": 13, "colno": 22 }

Upvotes: 2

Views: 109

Answers (3)

Spenser Black
Spenser Black

Reputation: 385

The JSON parser is receiving the value '{"a": """}', because the \ itself is not escaped. If you do

JSON.stringify({ "a": "\"" })

you will see that the stringified results are '{"a":"\\""}'.

Upvotes: 1

Shravan Dhar
Shravan Dhar

Reputation: 1560

The valid string to parse in your case should be:

const str = '{"a":"\\""}'
const parsedStr = JSON.parse(str);

console.log(parsedStr);

Explanation:

Following is invalid string initialization

const str = "\";

The valid syntax is:

const str = "\\";
console.log(str);

Therefore, \\ translates to \ (first one escapes the second one). The escaped \ is then used to esacape " in your case.

Further, output of this:

const str = "\\\\";
console.log(str);

const strWithQuote = "\\\"\\";
console.log("String with quote: ", strWithQuote);

Upvotes: 1

Musa
Musa

Reputation: 97717

You need 2 slashes in a string literal to represent a single slash in the string.
Or you can use a raw string template as well.

let a = JSON.parse('{"a": "\\""}');
let b = JSON.parse(String.raw`{"b": "\""}`);
console.log(a,b);

Upvotes: 3

Related Questions