WebMasterCampus
WEB DEVELOPER Resources

Javascript Pretty Print JSON Object

Learn how to Pretty Print JSON Object using Javascript


Javascript Pretty Print JSON Object

Printing JSON is easy with Javascript. We can achieve this using JSON.stringify().

JSON.stringify Syntax

JSON.stringify(value[, replacer[, space]])

Space argument is Optional. It can be a String or a Number object that’s used to insert white space into the output JSON string for readability purposes.

If this is a Number, it indicates the number of space characters to use as white space; this number is capped at 10 (if it is greater, the value is just 10). Values less than 1 indicate that no space should be used. If this is a String, the string (or the first 10 characters of the string, if it’s longer than that) is used as white space. If this parameter is not provided (or is null), no white space is used. JSON.stringify

Pretty Print JSON Example

function show(strValue) {
    document.body.appendChild(document.createElement('pre')).innerHTML = strValue;
}

var obj = {name:'Jessica', class:'Bootcamp', subjects:['Javascript','CSS','Python', 'NodeJS']};
var str = JSON.stringify(obj, undefined, 2);

show(str);

Pretty Print JSON Advanced Example

function show(strValue) {
    document.body.appendChild(document.createElement('pre')).innerHTML = strValue;
}

function colorfulSyntax(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 = {name:'Jessica', class:'Bootcamp', subjects:['Javascript','CSS','Python', 'NodeJS']};
var str = JSON.stringify(obj, undefined, 2);

show(colorfulSyntax(str));
Created with love and passion.