Home > Software engineering >  Escaping double quotation in javascript
Escaping double quotation in javascript

Time:05-14

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 }

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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":"\\""}'.

  • Related