需求:从数据库某个字段取出字符串出来,转为json,结果发现报错为 解析失败,发现是因为取出的字符串换行导致,现在需要将字符串里面的换行替换为'',使字符串可依成功解析成json对象。
技术:依靠replace函数实现
----------------------------------------
数据库里面的
----------------------------------------
{"choiceList":{"A":"
spare
fast
moderate
moral
----------------------------------------
去掉多余空格后的样子
----------------------------------------
{"choiceList":{"A":"
spare
","B":"fast
","C":"moderate
","D":"moral
"}}----------------------------------------
最后的解析成功的
----------------------------------------
{"choiceList": {"A": "
spare
","B": "fast
","C": "moderate
","D": "moral
"}}
关键代码:
var json=异常字符串
json = json.replace(/\n/g,"").replace(/\r/g,"");//去掉字符串中的换行符
json = json.replace(/\n/g,"").replace(/\s|\xA0/g,"");//去掉字符串中的所有空格
var jsonObj= eval('(' + json + ')'); //将字符串解析成json对象
console.log(jsonObj);
测试:
http://www.w3school.com.cn/tiy/t.asp?f=jquery_hide
","B":"\n\nfast \n\n
","C":"\n\n moderate\n\n
","D":"\n\nmoral\n\n
"}}';json= json.replace(/\n/g,"").replace(/\r/g,"").replace(/\s|\xA0/g,"");var jsonObj= eval('(' + json + ')');
console.log(jsonObj);
});
请在console控制台看结果