标签:htm 数据库 type ice col console ready eval 需要
需求:从数据库某个字段取出字符串出来,转为json,结果发现报错为 解析失败,发现是因为取出的字符串换行导致,现在需要将字符串里面的换行替换为‘‘,使字符串可依成功解析成json对象。
技术:依靠replace函数实现
----------------------------------------
数据库里面的
----------------------------------------
{"choiceList":{"A":"<p> <span>spare</span> </p>","B":"<p> <span>fast </span> </p>","C":"<p> <span>moderate</span> </p>","D":"<p> <span>moral</span> </p>"}}
----------------------------------------
去掉多余空格后的样子
----------------------------------------
{"choiceList":{"A":"<p><span>spare</span></p>","B":"<p><span>fast </span></p>","C":"<p><span>moderate</span></p>","D":"<p><span>moral</span></p>"}}
----------------------------------------
最后的解析成功的
----------------------------------------
{ "choiceList": { "A": "<p><span>spare</span></p>", "B": "<p><span>fast </span></p>", "C": "<p><span>moderate</span></p>", "D": "<p><span>moral</span></p>" } }
关键代码:
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 <!DOCTYPE html> <html> <head> <script src="/jquery/jquery-1.11.1.min.js"> </script> <script> $(document).ready(function(){ var json=‘{"choiceList": {"A2":"<p>\n\n<span> spare</span>\n\n</p>","B":"<p>\n\n<span>fast </span>\n\n</p>","C":"<p>\n\n<span> moderate</span>\n\n</p>","D":"<p>\n\n<span>moral</span>\n\n</p>"}}‘; json = json.replace(/\n/g,"").replace(/\r/g,"").replace(/\s|\xA0/g,""); var jsonObj= eval(‘(‘ + json + ‘)‘); console.log(jsonObj); }); </script> </head> <body> <p>请在console控制台看结果</p> </body> </html>
标签:htm 数据库 type ice col console ready eval 需要
原文地址:https://www.cnblogs.com/avivaye/p/9298265.html