Why does JSON.parse fail to parse this JSON string: `{ "Search results: \":s\"": "" }`?

718 Views Asked by At

Why does JSON.parse fail to parse the JSON string below?

Is this not valid JSON?

Strangely, https://jsonlint.com/ validates this string even though its custom JSON parser throws the same error as JSON.parse.

JSON string

{
    "Search results: \":s\"": ""
}

Code

let test = `{
    "Search results: \":s\"": ""
}`
JSON.parse(test);

Result

VM1882:2 Uncaught SyntaxError: Unexpected token s in JSON at position 22 at JSON.parse () at :1:6

1

There are 1 best solutions below

1
On

Use double backslashes to escape quotes in JavaScript strings that are meant to be be parsed as JSON:

let test = `{
  "Search results: \\":s\\"": ""
}`
console.log(JSON.parse(test));

{ 'Search results: ":s"': '' }

As noted in the comments above, the problem occurs when writing quotes in JavaScript code strings because the backslash itself has to be escaped to remain in the string as a backslash for JSON.parse in the future. JavaScript treats the first backslash in a string as an escape character, not as the literal character as necessary for this case. If the data is read from another source than JavaScript code, only a single backslash is necessary.