Why can't you parse a json with a \n
character in javascript
JSON.parse('{"x": "\n"}')
However when you do JSON.parse(JSON.stringify({"x" : "\n"}))
, it is valid.
http://www.jslint.com/ says that {"x": "\n"}
is a valid JSON. I wonder what does spec says about this?
Update: For those who marked this duplicate, this is not the same question as "How to handle newlines in JSON". This question is more about why can't an unescaped newline character allowed in JSON.
JSON.parse('{"x": "\n"}')
fails because '{"x": "\n"}'
is not a valid JSON string due to the unescaped slash symbol.
JSON.parse()
requires a valid JSON string to work.
'{"x": "\\n"}'
is a valid JSON string as the slash is now escaped, so JSON.parse('{"x": "\\n"}')
will work.
JSON.parse(JSON.stringify({"x" : "\n"}))
works because JSON.stringify internally escapes the slash character.
The result of JSON.stringify({"x" : "\n"})
is {"x":"\n"}
but if you try to parse this using JSON.parse('{"x":"\n"})'
it will FAIL, as it is not escaped. As JSON.stringify returns an escaped character, JSON.parse(JSON.stringify())
will work.
It need to be:
JSON.parse('{"x": "\\n"}')
You must use \\
to escape the character.
Why it's invalid?
It' from rfc4627 specs
All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F)." Since a newline is a control character, it must be escaped.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With