Skip to content

JavaScript pretty print JSON | Example code

  • by

Use the third argument in JSON.stringify() function to pretty print JSON in JavaScript. It will set space to display JSON in an easy-to-read.

JSON.stringify(jsObj, null, "\t"); // stringify with tabs inserted at each level
JSON.stringify(jsObj, null, 4);    // stringify with 4 spaces at each level

JavaScript pretty print JSON

Simple example code print JSON string in the console. JSON.stringify‘s third parameter defines white-space insertion for pretty-printing.

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

    console.log(data);

    var out = JSON.stringify(data, null, 4);
    console.log(out);

  </script>
  
</body>

</html

Output:

Read more: JavaScript pretty print JSON in HTML

Do comment if you have any doubts or suggestions on this JS print 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

Your email address will not be published. Required fields are marked *