Skip to content

JSON stringify pretty | JavaScript example

  • by

Using JSON stringify method with a third argument enables pretty printing and sets the spacing to use. Pretty printing is implemented natively in JSON stringify() method.

JSON.stringify(obj, null, 2); // spacing level = 2

The 3rd parameter to JSON.stringify() is called spaces.

JSON stringify pretty example

Simple HTML example code.

<!DOCTYPE html>
<html>
<body>

  <script>

    var obj = {a: "A100", b: "B100" }
    var string = JSON.stringify(obj, null,2);

    console.log(obj)
    console.log(string)

  </script>

</body>
</html

Output:

JSON stringify pretty

Another example

let data = {
    'username': 'John Doe',
    'email': '[email protected]',
    'state': 'married',
    'profiles': [
        {'name': 'jd7', 'job': 'actor' },
        {'name': 'johnd7', 'job': 'spy'}
    ],
    'active': true,
    'employed': true
};

console.log(JSON.stringify(data, null, 2));

Output:

{
  "username": "John Doe",
  "email": "[email protected]",
  "state": "married",
  "profiles": [
    {
      "name": "jd7",
      "job": "actor"
    },
    {
      "name": "johnd7",
      "job": "spy"
    }
  ],
  "active": true,
  "employed": true
}

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

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

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Discover more from Tutorial

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

Continue reading