Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing JSON like console.log prints it in Node.js

Wondering if it's possible to print JSON like Node.js prints it out. If there is some standard module or something to do that.

enter image description here

It has the spacing between keys, and when it's too long it goes onto a new line, etc. The coloring would be a bonus.

JSON.stringify(object, null, 2) pretty prints the JSON, wondering if there is something more hidden in there, or any standards, for doing it like Node.js does. Thank you.

like image 501
Lance Avatar asked Dec 23 '17 01:12

Lance


1 Answers

This seems to be achievable by using util.inspect():

const util = require('util');

const testJson = `{
    "id": "0001",
    "type": "donut",
    "name": "Cake",
    "ppu": 0.55,
    "batters":
        {
            "batter":
                [
                    { "id": "1001", "type": "Regular" },
                    { "id": "1002", "type": "Chocolate" },
                    { "id": "1003", "type": "Blueberry" },
                    { "id": "1004", "type": "Devil's Food" }
                ]
        },
    "topping":
        [
            { "id": "5001", "type": "None" },
            { "id": "5002", "type": "Glazed" },
            { "id": "5005", "type": "Sugar" },
            { "id": "5007", "type": "Powdered Sugar" },
            { "id": "5006", "type": "Chocolate with Sprinkles" },
            { "id": "5003", "type": "Chocolate" },
            { "id": "5004", "type": "Maple" }
        ]
}`

x = JSON.parse(testJson);
x.x = x;
console.log(util.inspect(x, { colors: true }));

with depth=2

The options object takes a parameter called depth that determines how deep it will recurse. The default value is 2. If I increase it to 3:

console.log(util.inspect(x, { colors: true, depth: 3 }));

I get the following:

with depth=3

To make it recurse indefinitely pass depth: null. The default value seems to be 2 in the node cli as well.

like image 57
Mika Sundland Avatar answered Nov 15 '22 03:11

Mika Sundland