Javascript 解析包含换行符的 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11591784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Parsing JSON containing new line characters
提问by Preli
In my website I try to convert a string to JSON which contains a newline.
在我的网站中,我尝试将字符串转换为包含换行符的 JSON。
JSON.parse('{"hallo":"line1\r\nline2","a":[5.5,5.6,5.7]}');
This produces an "Unexpected token" error. Do I need to escape that somehow?
这会产生“意外令牌”错误。我需要以某种方式逃避吗?
回答by madfriend
Yes, you should escape both \n
and \r
as they belong to the list of control characters. Full list of characters that need to be escaped can be found here. Your code would be
是的,您应该对两者进行转义\n
,\r
因为它们属于控制字符列表。可以在此处找到需要转义的字符的完整列表。你的代码是
obj = JSON.parse('{"hallo":"line1\r\nline2","a":[5.5,5.6,5.7]}');
JSFiddle: link
JSFiddle:链接
回答by Daniel Earwicker
Try:
尝试:
JSON.parse('{"hallo":"line1\r\nline2","a":[5.5,5.6,5.7]}');