JSON.parse with newline [duplicate]

╄→尐↘猪︶ㄣ 提交于 2020-01-02 03:30:11

问题


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.


回答1:


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.




回答2:


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.




回答3:


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".




回答4:


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.



来源:https://stackoverflow.com/questions/29666036/json-parse-with-newline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!