This question already has answers here:
Closed 5 years ago.
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.
In JavaScript "\n"
is not the literal string \n
. It is a string containing a newline character. That makes your JSON invalid.
To represent the literal string \n
, you need to escape the initial backslash character with another backslash character: "\\n"
.
You need to escape the "\
" in your string (turning it into a double-"\\
"), otherwise it will become a newline in the JSON
source, not the JSON data
.
Try to replace \n
with some other characters while parsing and again replace those characters with \n
before assigning this value to some control.