我得到以下字符串:
var str='{"message":"hello\nworld"}';
我需要将其转换为 JSON 对象。但是,由于 \n
JSON.parse(str)
时出现异常
我看到了this问题,但没有帮助。
由此,我尝试了
var j=JSON.parse(JSON.stringify(str))
但是当我使用 typeof j
我知道使用 \\n
是可行的,但问题是,当我需要使用该值时,它不会在新行上打印。
更新:好的,我刚刚意识到 \\n
正在工作。
我正在使用它来将 \n
转换为 \\n
:
var str='{"message":"hello\nworld"}';
str=str.replace(/\n/g, "\\\\n").replace(/\r/g, "\\\\r").replace(/\t/g, "\\\\t");
var json=JSON.parse(str);
console.log(json.message);
有人可以更正一下吗?
最佳答案
将 \n
转义为 \\n
是正确的做法。在您的代码中,替换调用做错了。你需要更少的斜杠。更新了您的代码:
var str='{"message":"hello\nworld"}';
str=str.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
var json=JSON.parse(str); //No errors due to escaping
现在打印它,您会看到文本被分成不同的行。
console.log(json.message);
关于javascript - JSON.parse 给出字符串中换行符的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37810964/