Skip to content

Display raw JSON data in HTML | Example code

  • by

Using the JSON stringify method you can Display raw JSON data in HTML. Use the third argument which enables pretty printing and sets the spacing to use.

Sample JSON data:

var jsonVar = {
        text: "example",
        number: 1
    };

Then you need only do this to convert it to a string:

var jsonStr = JSON.stringify(jsonVar);

And then you can insert into your HTML directly, for example:

document.body.innerHTML = jsonStr;

You can replace body with some other element via getElementById.

Source: stackoverflow.com

Display raw JSON data in HTML

Simple example code using pre-tag to show JSON data, you can use any tag.

<!DOCTYPE html>
<html>

<body>
  <pre id="jtext"></pre>

  <script>
    var obj =  {
     "msg":"Hello",
     "anumber":243,
     "anobject":{
      "whoa":"nuts",
      "anarray":[1,2, "three"],
      "more":"stuff"
    },
    "awesome":true,
    "bogus":false,
    "meaning":null,
    "japanese":"明日がある。",
    "link":"http://eyehunts.com",
  }

  var str = JSON.stringify(obj, null, 2);
  document.getElementById("jtext").innerHTML = str;


</script>

</body>
</html> 

Output:

Display raw JSON data in HTML

Do comment if you have any doubts or suggestions on this JS JSON topic.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading