解析包含换行符的JSON [英] Parsing JSON containing new line characters

查看:516
本文介绍了解析包含换行符的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网站中,我尝试将字符串转换为包含换行符的JSON。

In my website I try to convert a string to JSON which contains a newline.

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?

推荐答案

是的,你应该同时逃避 \ n \ r 因为它们属于控制字符列表。可以在此处找到需要转义的完整字符列表。你的代码将是

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

obj = JSON.parse('{"hallo":"line1\\r\\nline2","a":[5.5,5.6,5.7]}');

JSFiddle:链接

JSFiddle: link

这篇关于解析包含换行符的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆