Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 501
Preli Avatar asked Jul 21 '12 11:07

Preli


People also ask

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.

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 escape a JSON string containing newline characters in Java?

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, '\\"') .


2 Answers

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

like image 66
madfriend Avatar answered Sep 26 '22 13:09

madfriend


Try:

JSON.parse('{"hallo":"line1\\r\\nline2","a":[5.5,5.6,5.7]}'); 
like image 41
Daniel Earwicker Avatar answered Sep 24 '22 13:09

Daniel Earwicker