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?

Answers:

Answer

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

Answer

Try:

JSON.parse('{"hallo":"line1\\r\\nline2","a":[5.5,5.6,5.7]}');

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.