JSON.parse给string中的换行符赋予exception

我收到以下string:

var str='{"message":"hello\nworld"}';

我需要把它变成JSON对象。 但是,由于\n ,我尝试使用JSON.parse(str)时出现exception

我看到这个问题,但没有帮助。

从那以后,我试着var j=JSON.parse(JSON.stringify(str))

但是当我使用typeof j时,我仍然得到string而不是对象

我知道使用\\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是正确的做法。 在你的代码中,replace调用是错误的。 你需要更less的斜杠。 更新你的代码:

 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);