Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON.stringify output to div in pretty print way

People also ask

How do I pretty print a JSON string?

Use JSON. stringify(obj) method to convert JavaScript objects into strings and display it. Use JSON. stringify(obj, replacer, space) method to convert JavaScript objects into strings in pretty format.

How do I beautify JSON in HTML?

use a <pre> tag to JavaScript pretty prints JSON in HTML. The <pre> need id to show data on it. Where pre tells the browser engine that the content inside is pre-formatted and can be displayed without any modification. To convert it to JSON and pretty print use stringify method.

How do I pretty print a JSON object?

Use json. dumps() method to prettyprint JSON properly by specifying indent and separators. The json. dumps() method returns prettyprinted JSON data in string format.

Which pipe is used for pretty printing the JSON value?

Angular json pipe is also useful for debugging purpose because it displays all the properties of the object in pretty print json format.


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.


My proposal is based on:

  • replace each '\n' (newline) with a <br>
  • replace each space with &nbsp;

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


document.querySelector('#newquote').innerHTML = JSON.stringify(x, null, 6)
     .replace(/\n( *)/g, function (match, p1) {
         return '<br>' + '&nbsp;'.repeat(p1.length);
     });
<div id="newquote"></div>

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));
    }

Full disclosure I am the author of this package but another way to output JSON or JavaScript objects in a readable way complete with being able skip parts, collapse them, etc. is nodedump, https://github.com/ragamufin/nodedump