36

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?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Preli
  • 2,953
  • 10
  • 37
  • 50
  • 2
    Why do you write JSON manually? – Esailija Jul 21 '12 at 11:33
  • 4
    I don't! The json line is beeing generated by another program which obviously doesn't escape those characters correctly. – Preli Jul 21 '12 at 11:49
  • 2
    In that case the program is correct and you placed `JSON.parse('` and `');` manually. The program's output is likely `{"hallo":"line1\r\nline2","a":[5.5,5.6,5.7]}` which is correct. You do not need to make a javascript string out of it, it's already valid javascript in an expression context by itself. All you needed was `var a = programOutput;` directly without any interference. – Esailija Jul 21 '12 at 11:54
  • No, the programs output is exactly this line including JSON.parse; whoever made it had obviously no idea about JavaScript – Preli Jul 21 '12 at 12:42

2 Answers2

39

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

Community
  • 1
  • 1
madfriend
  • 2,400
  • 1
  • 20
  • 26
  • 2
    Upvoted this answer because it contains an extra line of "explanation" :P – Alvin Wong Jul 21 '12 at 11:35
  • Silly me. I only tried escaping the \n and totally forgot about the \r. Thank you, it is working now. – Preli Jul 21 '12 at 11:44
  • is there a function to escape those characters? – Throoze Oct 06 '13 at 10:11
  • Actually, I had to "double escape" to have the new line reaching the HTML. I take the value from the database then do a replaceAll("\n","\\\\n").reaplaceAll("\r","\\\\r") and all is fine now :D – Cedric Simon Nov 22 '13 at 17:13
  • 2
    @Throoze - yes, there is. JSON.stringify(str) will return a string containing a quoted, escaped JS string literal for `str`. For example, `JSON.stringify("\n").length` evaluates to `4`, because the returned string will have two quotes, a backslash and an `n`, just like the literal passed into it. – Daniel Earwicker Nov 10 '14 at 09:46
  • Am I missing something here? I'm not seeing two lines in the fiddle link. – lorless Nov 11 '15 at 11:32
5

Try:

JSON.parse('{"hallo":"line1\\r\\nline2","a":[5.5,5.6,5.7]}');
Daniel Earwicker
  • 114,894
  • 38
  • 205
  • 284