Dushyant Bangal
Dushyant Bangal

Reputation: 6403

JSON.parse gives exception with newline character in string

I'm getting the following string:

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

I need to turn it into JSON object. However, I get an exception when I try JSON.parse(str) because of the \n

I saw this question but it did not help.

From that, I tried var j=JSON.parse(JSON.stringify(str))

But I'm still getting string instead of object when i use typeof j

I know using \\n works, but the thing is, it does not print on new line when i need to use the value.

UPDATE: OK, i just realized \\n is working. I'm using this to convert \n to \\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);

Can someone please correct it?

Upvotes: 7

Views: 10112

Answers (1)

EnKrypt
EnKrypt

Reputation: 777

Escaping \n to \\n was the right thing to do. In your code, the replace call was done wrong. You need fewer slashes. Updated your code :

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

Now print it and you'll see the text being split into different lines.

console.log(json.message);

Upvotes: 13

Related Questions