Parsing JSON containing new line characters [duplicate]
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?
Solution 1:
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
Solution 2:
Try:
JSON.parse('{"hallo":"line1\\r\\nline2","a":[5.5,5.6,5.7]}');