Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preserving linebreaks in values in JSON key-value pairs

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.

like image 750
punkish Avatar asked Nov 15 '11 01:11

punkish


1 Answers

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.

like image 178
PhoneixS Avatar answered Oct 03 '22 06:10

PhoneixS