In my website I try to convert a string to JSON which contains a newline.
JSON.parse('{"hallo":"line1\r\nline2","a":[5.5,5.6,5.7]}');
This produces an "Unexpected token" error. Do I need to escape that somehow?
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.
JSON strings do not allow real newlines in its data; it can only have escaped newlines.
To escape a JSON string containing newline characters using JavaScript, we can call string replace to replace various characters. const escape = (str) => { return str . replace(/[\\]/g, "\\\\") . replace(/[\"]/g, '\\"') .
Yes, you should escape both \n
and \r
as they belong to the list of control characters. Full list of characters that need to be escaped can be found here. Your code would be
obj = JSON.parse('{"hallo":"line1\\r\\nline2","a":[5.5,5.6,5.7]}');
JSFiddle: link
Try:
JSON.parse('{"hallo":"line1\\r\\nline2","a":[5.5,5.6,5.7]}');
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