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?
.box is just an empty div.
Make it an empty <pre>
instead:
<pre class="box"></pre>
I agree with using <pre>
, but another option is to replace all \n
with <br>
elements, and spaces with
. 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, " ");
console.log(results);
$(".box").append(results2);
DEMO: http://jsfiddle.net/Yk5Pb/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With