Display formatted JSON in HTML | Example code

  • by

Use the JSON.stringify function to Display formatted JSON in HTML. If you have unformatted JSON It will output it in a formatted way.

JSON.stringify({ foo: "sample", bar: "sample" }, null, 4)

This turns

{ "foo": "sample", "bar": "sample" }

into

 {
     "foo": "sample", 
     "bar": "sample" 
 }

Source: stackoverflow.com

Or Use <pre> tag for showing code itself in HTML page and with JSON.stringify().

document.getElementById("beautified").innerHTML = JSON.stringify(data, undefined, 2);

Display formatted JSON in HTML

Simple example code to show formatted JSON in HTML. For this you have to use pre tag, otherwise, it does not look good.

The JSON.stringify() method converts a JavaScript object or value to a JSON string.

<!DOCTYPE html>
<html>
<body>

  <pre id="myText" ></pre>

  <script>
    var data = { foo: "sample", bar: "sample" };

    document.getElementById("myText").innerHTML = JSON.stringify(data, null, 4);
    
  </script>

</body>

</html

Output:

Display formatted JSON in HTML

More code

<!DOCTYPE html>
<html>
<body onload="myFunction()">
  <script>
    function myFunction() {
      var data = {
        "data": {
          "x": "1",
          "y": "1",
          "url": "http://test.com"
        },
        "event": "start",
        "show": 1,
        "id": 50
      }


      document.getElementById("json").innerHTML = JSON.stringify(data, undefined, 2);
    }

  </script>
  <pre id="json"></pre>
</body>

</html

Output:

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

Do comment if you have any doubts or suggestions on this HTML code.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.