7

I am not sure if line breaks are allowed in JSON values. I certainly am unable to create the following in JSON

{"foo": "I am not sure if line breaks are 
         allowed in JSON values. I certainly 
         am unable to create the following in JSON"}

The following certainly does not work

{"foo": "I am not sure if line breaks are\nallowed in JSON values. I certainly\nam unable to create the following in JSON"}

Preamble: I want to send a long message like above either to the browser or to the console app and display it neatly formatted so it is legible to the user.

Faruk Sahin
  • 8,406
  • 5
  • 28
  • 34
punkish
  • 13,598
  • 26
  • 66
  • 101

2 Answers2

1

If you are displaying (or inserting) the json value directly in HTML, you can't use it as it is because in html new lines are ignored and replaced by a space.

For example if you have:

<p>Hello,
I'm in other line.</p>

It will be represented as:

Hello, I'm in other line.

You must convert the new lines to paragraph or <br>, for example:

<p>Hello,<br>
I'm in other line.</p>

That will be show as:

Hello,

I'm in other line

If this is your case, you can simply use String.replace to change \n into <br>\n.

PhoneixS
  • 10,574
  • 6
  • 57
  • 73
0

If you're displaying it in HTML,
will simple do. Or in a text area or something, try "\r\n", wrapped in double quotes. Double backslashes are to escape.

Moe Sweet
  • 3,683
  • 2
  • 34
  • 46