Mosho Mosho - 6 months ago 77
JSON Question

JSON.parse parses JSON.stringify output but not string itself

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.

Answer

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.

Comments