[Solved-6 Solutions] pretty-print JSON using javascript - JavaScript Tutorial



Problem:

How can we pretty-print JSON using JavaScript ?

Solution 1:

In javascript JSON.stringify() method converts into value of JSON string.

console.log(JSON.stringify({ x: 7, y: 8 }));
// expected output: "{"x":7,"y":8}"

console.log(JSON.stringify([new Number(4), new String('false'), new Boolean(false)]));
// expected output: "[4,"false",false]"

console.log(JSON.stringify({ x: [8, undefined, function(){}, Symbol('')] }));
// expected output: "{"x":[8,null,null,null]}"

console.log(JSON.stringify(new Date(2008, 0, 2, 15, 4, 5)));
// expected output: ""2008-01-02T15:04:05.000Z""

Solution 2:

To display JSON in an easy-to-read format for indentation and whitespace, with perhaps even colors / font-styles / etc.

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

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

function syntaxHighlight(json) 
{
    if (typeof json != 'string') 
    {
         json = JSON.stringify(json, undefined, 2);
    }
    json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
    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>';
    });
}

Solution 3:

We have an object to be printed as pretty . Only valid JSON string process to be occur, we want to convert it to an object first:

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

It is create a JSON object from the string, and then converts to a string using JSON stringify's as pretty to be print.

Read Also

AngularJS JSONt

Solution 4:

We can use console.dir(), it is expand as console.log(util.inspect()).

It uses syntax-highlighting, smart indentation, removes quotes from keys and the output gets as pretty.

const object = JSON.parse(jsonString)

console.dir(object, {depth: null, colors: true})

and for the command line:

cat package.json | node -e "process.stdin.pipe(new stream.Writable({write: chunk => console.dir(JSON.parse(chunk), {depth: null, colors: true})}))"

Solution 5:

We use this code for debugging :

console.debug("%o", data);

Solution 6:

It works well:

console.table()


Related Searches to javascript tutorial - pretty-print JSON using javascript