Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.parse with newline [duplicate]

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.

like image 769
Juzer Ali Avatar asked Apr 16 '15 05:04

Juzer Ali


2 Answers

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.

like image 114
philz Avatar answered Oct 15 '22 22:10

philz


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.

like image 1
mohamedrias Avatar answered Oct 15 '22 23:10

mohamedrias