javascripthtmljsonpretty-printstringify

JSON.stringify output to div in pretty print way


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?


Solution

  • 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>