Categories
javascript json pretty-print

pretty-print JSON using JavaScript

3106

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.

2

  • 16

    If you’re just outputting to html, you can wrap it in a <pre> tag.

    Mar 30, 2018 at 4:36


  • all answer will work but you have to use javascript :: var str = JSON.stringify(obj, null, 2); in html // <pre id=”output_result_div”></pre >

    Feb 2, 2021 at 13:17

6281

+100

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>';
    });
}

See in action here: jsfiddle

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; }

5

  • 31

    Super awesome. I added a function to pop open this in a new window for debugging: var json = syntaxHighlight(JSON.stringify(obj,undefined,4);); var w = window.open(); var html = “<head><style>pre {outline: 1px solid #ccc; padding: 5px; margin: 5px; } .string { color: green; } “; html+= ” .number { color: darkorange; } .boolean { color: blue; } .null { color: magenta; } .key { color: red; }</style></head><body>”; html+= “<pre>”+json+”</pre>”; w.document.writeln(html);

    Jul 30, 2012 at 2:07


  • 36

    Nice. Don’t forget it needs css and a <pre>, though.

    – NoBugs

    Jun 4, 2013 at 5:37

  • 101

    Note that stringify(...) works on JSON objects, not on JSON strings. If you have a string, you need to JSON.parse(...) first

    – Vihung

    Aug 5, 2014 at 12:40

  • 1

    i built a tool on this sardapv.github.io/json-prettier 🙂

    – minigeek

    Jul 3, 2021 at 10:47

  • Hello, this is awesome. It works but I get a lint warning on the second-to-last backslash in the regex- Unnecessary escape character: \- no-useless-escape. I don’t have it unit tested so afraid to // eslint-disable-next-line

    – fotoflo

    Jun 6 at 22:03


376

User Pumbaa80’s answer is great if you have an object you want pretty printed. If you’re starting from a valid JSON string that you want to pretty printed, you need to convert it to an object first:

var jsonString = '{"some":"json"}';
var jsonPretty = JSON.stringify(JSON.parse(jsonString),null,2);  

This builds a JSON object from the string, and then converts it back to a string using JSON stringify’s pretty print.

2

  • 38

    Note that when displaying the string you need to wrap it in <pre></pre> tags.

    Feb 10, 2017 at 16:05

  • It seems to only work when using textarea, otherwise the newlines don’t come in

    Nov 7, 2021 at 2:11

93

Better way.

Prettify JSON Array in Javascript

JSON.stringify(jsonobj,null,'\t')

0