How to pretty print (beautify) a JSON String

The JSON stringify method returns a JSON string from an array or an object. This method expects 3 parameters:

  • value (Object or array)
  • Replacer or Filter (function to process or array of strings with the indexes to show)
  • space (Pretty print your json with spaces or line breaks)
var value = {
  hello:"Hey!",
  bye: "Ok bye!",
  id:123
}; // An array or an object

//A function that alters the behavior of the stringification process, 
// or an array of Strings and Numbers objects that serve as a whitelist for selecting the properties of the value object to be included in the JSON string. 
// If this value is null or undefined, all properties of the object are included in the resulting JSON string
var replacer = ["hello"];

// or a function
// In this case only the id property of the object will be stringified as this is the only property with a numeric value.
function replacer(key, value) {
  if (typeof value === "number") {
    return undefined;
  }
  return value;
}

// a numeric value which is identified as spaces
// or use custom separators (line breaks \t or \n ) 
var space = 5;


JSON.stringify(value, replacer, space);

You can pretty-print a json object using the third parameter. Very useful if you work with cordova or node.js in order to create organized .json files.

The following example show how to pretty print (indented json) a json object with JSON.stringify and give a highlight style with css :

The syntaxHighlight function will add to every property a span with a custom class to give a highlight effect in the div element. You can even to give a highlight style in the chrome console using css, read more about how css works in the console here

The following function will handle the generated pretty-printed json string by the JSON.stringify function and will print it with colors in the console.

function PrettyPrintJsonConsole(json) {
    if (typeof json != 'string') {
        json = JSON.stringify(json, undefined, '\t');
    }

    var 
        arr = [],
        _string = 'color:green',
        _number = 'color:darkorange',
        _boolean = 'color:blue',
        _null = 'color:magenta',
        _key = 'color:red';

    json = json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
        var style = _number;
        if (/^"/.test(match)) {
            if (/:$/.test(match)) {
                style = _key;
            } else {
                style = _string;
            }
        } else if (/true|false/.test(match)) {
            style = _boolean;
        } else if (/null/.test(match)) {
            style = _null;
        }
        arr.push(style);
        arr.push('');
        return '%c' + match + '%c';
    });

    arr.unshift(json);

    console.log.apply(console, arr);
}

var myCustomObject = {
  numbers:[1,3,4,5],
  hello:"Hey there!",
  otherThing:true,
  anotherThing:4
};

PrettyPrintJsonConsole(JSON.stringify(myCustomObject,null,4));

The use of the previous function, should output something like this in the chrome console:

Chrome pretty-print JSON

Have fun !

This could interest you

Become a more social person