Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 787
Dushyant Bangal Avatar asked Jun 14 '16 11:06

Dushyant Bangal


People also ask

Can JSON have new line character?

JSON strings do not allow real newlines in its data; it can only have escaped newlines.

How do you pass a new line character in JSON?

In JSON object make sure that you are having a sentence where you need to print in different lines. Now in-order to print the statements in different lines we need to use '\\n' (backward slash). As we now know the technique to print in newlines, now just add '\\n' wherever you want.

What happens if you JSON parse a string?

The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

How do you escape a JSON string containing newline characters in Java?

replace(/\\t/g, "\\t") .


1 Answers

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);
like image 178
EnKrypt Avatar answered Nov 01 '22 10:11

EnKrypt