如果json字符串中包含了换行符"\n",直接解析的话就会发生Uncaught SyntaxError: Unexpected token ILLEGAL 错误,很显然需要转换成"\\n",但是不能直接改成"\\n"不然本来不是换行也当成了换行,应该用正则表达式去做如下替换
function say_hello(){ var data = ‘{"count" : 1, "stack" : "sometext\n\n"}‘; data = data.replace(/\n/g, "\\\\n"); var dataObj = eval(‘(‘+data+‘)‘); console.log(dataObj); } say_hello();
http://jsfiddle.net/yyh19890221/r9bh2gb7/
时间: 2024-11-05 19:44:38