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?
JSON strings do not allow real newlines in its data; it can only have escaped newlines.
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.
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.
replace(/\\t/g, "\\t") .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With