12

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?

2 Answers 2

23

.box is just an empty div.

Make it an empty <pre> instead:

<pre class="box"></pre>
Sign up to request clarification or add additional context in comments.

2 Comments

The major problem about pre tag is that there is no scrollbar.
@cn123h Thats not true. Try setting the element's css with overflow: auto. Worked for me on latest version of Chrome.
8

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.