2

I just got this in the Chrome console:

JSON.stringify(({wat:"\""}))
> "{"wat":"\""}"
JSON.parse(JSON.stringify(({wat:"\""})))
> Object {wat: """}
JSON.parse('{"wat":"\""}')
> VM34235:1 Uncaught SyntaxError: Unexpected string in JSON at position 9(…)

Screenshot:

shenanigans

JSON.parse successfully parses when passed the output of JSON.stringify({wat:"\""}) but throws when I try to eval JSON.parse('{"wat":"\""}').

I'm calling shenanigans.

4
  • Look at the string value of '{"wat":"\""}'. It should be pretty clear then. Commented May 21, 2016 at 0:52
  • '{"wat":"\""}' === '{"wat":"""}'; // true, you need to escape your backslash Commented May 21, 2016 at 0:57
  • If you look at the console output ("{"wat":"\""}"), you can see that the value is not a valid string literal, because it doesn't show escape sequences. Otherwise it would have to look like "{\"wat\":\"\\\"\"}". Hence you cannot simply copy and paste the output into a string literal. What the console shows you is the string value. This might become more obvious if you type 'foo\nbar' into the console. Commented May 21, 2016 at 1:00
  • Yeah, I should have figured that out. I was debugging some code which put a stringified object into a template string which was eval'd later, and tried to parse the same, confused me enough to forget about proper escaping... Commented May 21, 2016 at 1:03

2 Answers 2

5

The quote character has to be escaped with two backslashes, like that:

JSON.parse('{"wat":"\\""}')

When it's escaped with only one backslash, JSON.parse() actually gets the following value to parse:

{"wat":"""}

which is of course invalid JSON.

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

1 Comment

Can't he just add more double qoutes as well? \"""
0

Try adding 2 backslashes like this. JS sees the \ as an escape character and ignores it. So:

{wat:"\\""}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.