Home >Web Front-end >JS Tutorial >An error occurs when using JSON.parse to convert a json string into a json object_javascript tips

An error occurs when using JSON.parse to convert a json string into a json object_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:37:271280browse

在对数据库取出来的数据(特别是描述信息)里面含有特殊字符的话,使用JSON.parse将json字符串转换成json对象的时候会出错,主要是双引号,回车换行等影响明显,左尖括号和右尖括号也会导致显示问题,所以要在输出到页面进行json对象转换之前将一些特殊符合进行编码或转义,下面展示的是C#代码编码和转义几个常用特殊字符。经过笔者测试,将这些符号编码和转义之后,大部分json字符串都可以转换成json对象了。如果遇到个别问题,应朝着这个方向去查找问题。

theString = theString.Replace(">", ">"); 
theString = theString.Replace("<", "<"); 
theString = theString.Replace(" ", " "); 
theString = theString.Replace("\"", """); 
theString = theString.Replace("\'", "&#39;"); 
theString = theString.Replace("\\", "\\\\");//对斜线的转义 
theString = theString.Replace("\n", "\\n"); 
theString = theString.Replace("\r", \\r);

注意: 是回到行首,\n是新启一行,这两个一般同时出现,应该同时处理。

补充:文字中间的换行,空格在数据库里面不以 \n, ;等形式显示出来(“本书”与“前80”之间换行,“由”与“曹雪芹”之间空格)

文字:

数据库:

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn