pretty-print JSON using JavaScript

Asked : Nov 17

Viewed : 113 times

How can I display JSON in an easy-to-read (for human readers) format? I'm looking primarily for indentation and whitespace, with perhaps even colors / font-styles / etc.

json javascript pretty-print 
4 Answers

Pretty-printing is implemented natively in JSON.stringify(). The third argument enables pretty printing and sets the spacing to use:

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

If you need syntax highlighting, you might use some regex magic like so:

function syntaxHighlight(json) {
    if (typeof json != 'string') {
         json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

Or a full snippet provided below:

function output(inp) {
    document.body.appendChild(document.createElement('pre')).innerHTML = inp;
}

function syntaxHighlight(json) {
    json = json.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
    return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var cls = 'number';
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                cls = 'key';
            } else {
                cls = 'string';
            }
        } else if (/true|false/.test(match)) {
            cls = 'boolean';
        } else if (/null/.test(match)) {
            cls = 'null';
        }
        return '<span class="' + cls + '">' + match + '</span>';
    });
}

var obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]};
var str = JSON.stringify(obj, undefined, 4);

output(str);
output(syntaxHighlight(str));
pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; }
.string { color: green; }
.number { color: darkorange; }
.boolean { color: blue; }
.null { color: magenta; }
.key { color: red; }

answered Jan 28


f you're looking for a nice library to prettify json on a web page...

Prism.js is pretty good.

http://prismjs.com/

I found using JSON.stringify(obj, undefined, 2) to get the indentation, and then using prism to add a theme was a good approach.

If you're loading in JSON via an ajax call, then you can run one of Prism's utility methods to prettify

For example:

Prism.highlightAll()

answered Jan 28


This example uses JSON.stringify() method to print the object element within <pre> tag.

<!DOCTYPE html>
<html>
  
<head>
    <title>
        How to pretty print JSON
        string in JavaScript ?
    </title>
</head>
  
<body>
    <h1 style="color:green;"> 
        GeeksforGeeks 
    </h1>
      
    <p id="GFG_UP" style=
        "font-size: 15px; font-weight: bold;">
    </p>
      
    <button onclick="gfg_Run();">
        click here
    </button>
      
    <pre id="GFG_DOWN" style=
        "color:green; font-size: 20px; font-weight: bold;">
    </pre>
      
    <script>
        var el_up = document.getElementById("GFG_UP");
        var el_down = document.getElementById("GFG_DOWN");
        var obj = {
            "prop_1": {
                "prop_11": "val_11",
                "prop_12": "val_12"
            },
            "prop_2": "val_2",
            "prop_3": "val_3"
        };
      
        el_up.innerHTML = JSON.stringify(obj);
  
        function gfg_Run() {
            el_down.innerHTML = JSON.stringify(obj, undefined, 4);
        }
    </script>
</body>
  
</html>          

answered Jan 28


JSON.stringify

The JSON.stringify function converts a JavaScript object or value to a JSON string. We can use the function to pretty print JSON output. Note that on terminal, the console.log and console.dir functions automatically pretty print JSON data. The output is also coloured on terminals that support coloured output.

Web browsers do not automatically pretty print JSON output; we can prettify the JSON output with JSON.stringify.

JS JSON pretty print with JSON.stringify

The JSON.stringify function has a space option, which inserts white space into the output JSON string for readability purposes. The maximum value for space is 10; a value smaller than 1 provides no space.

stringify.jslet 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));

In the example, we add 2 space characters to the JSON output. We don't use the replacer, so we pass null as the second argument.

answered Jan 28


Login and Submit Your Answer
Browse other questions tagged  json  javascript  pretty-print or ask your own question.