Display JSON object in DIV [duplicate]

I JSON.stringify a json object by

result = JSON.stringify(message, my_json, 2)

The 2 in the argument above is supposed to pretty print the result. It does this if I do something like alert(result). However, I want to output this to the user by appending it inside a div. When I do this I get just a single line showing up. (I don't think it is working because the breaks and spaces are not being interpreted as html?)

{ "data": { "x": "1", "y": "1", "url": "http://url.com" }, "event": "start", "show": 1, "id": 50 }

Is there a way to output the result of JSON.stringify to a div in a pretty print way?


Please use a <pre> tag

demo : http://jsfiddle.net/K83cK/

var data = {
  "data": {
    "x": "1",
    "y": "1",
    "url": "http://url.com"
  },
  "event": "start",
  "show": 1,
  "id": 50
}


document.getElementById("json").textContent = JSON.stringify(data, undefined, 2);
<pre id="json"></pre>

Make sure the JSON output is in a <pre> tag.


If your <pre> tag is showing a single-line of JSON because that's how the string is provided already (via an api or some function/page out of your control), you can reformat it like this:

HTML:

<pre id="json">{"some":"JSON string"}</pre>

JavaScript:

    (function() {
        var element = document.getElementById("json");
        var obj = JSON.parse(element.innerText);
        element.innerHTML = JSON.stringify(obj, undefined, 2);
    })();

or jQuery:

    $(formatJson);

    function formatJson() {
        var element = $("#json");
        var obj = JSON.parse(element.text());
        element.html(JSON.stringify(obj, undefined, 2));
    }