0

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

7
  • The backslash characters quote the " characters for the outer-level string. You have to double the backslashes because there are two parsing phases. Commented Apr 25, 2021 at 0:34
  • or you have to let test = String.raw`{ ... }` Commented Apr 25, 2021 at 0:37
  • @Pointy thanks for the fast response. to clarify, jsonlint.com is wrong to consider this JSON valid? Commented Apr 25, 2021 at 0:47
  • @Thomas using String.raw seems to work. do you know why? also would you like to post as an answer? Commented Apr 25, 2021 at 0:48
  • 2
    No, jsonlint.com is not wrong, this is valid JSON. The problem is you're typing it verbatim into a JavaScript document without escaping it for JavaScript. If you placed the identical contents into a text file, loaded the text file and then parsed the contents as JSON, it would work fine. Commented Apr 25, 2021 at 0:58

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks. this helped us find the root cause. the question was a simplified version of the problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.