Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON in HTML with line breaks

I have some Javascript on my page that makes an ajax call which returns some JSON data.

With the result I do this:

results = JSON.stringify(data, undefined, 2);
console.log(results);
$('.box').append(results);

.box is just an empty div.

console.log(results) gives me an indented result with linebreaks but the data in .box is just all in one line.

How can I make sure that the result in .box is also on multiple lines and indented?

like image 626
Oskar Persson Avatar asked May 11 '13 17:05

Oskar Persson


2 Answers

.box is just an empty div.

Make it an empty <pre> instead:

<pre class="box"></pre>
like image 74
Darin Dimitrov Avatar answered Sep 22 '22 16:09

Darin Dimitrov


I agree with using <pre>, but another option is to replace all \n with <br> elements, and spaces with &nbsp;. It's probably really unnecessary (since <pre> preserves the whitespace). You can try:

var data = {key1: "value1", key2: "value2", key3: {key4: "value4"}},
    results = JSON.stringify(data, undefined, 2),
    results2 = results.replace(/\n/g, "<br>").replace(/[ ]/g, "&nbsp;");
console.log(results);
$(".box").append(results2);

DEMO: http://jsfiddle.net/Yk5Pb/3/

like image 35
Ian Avatar answered Sep 22 '22 16:09

Ian