Printing JSON like console.log prints it in Node.js
Asked Answered
D

1

5

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.

Devoirs answered 23/12, 2017 at 1:15 Comment(0)
G
14

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.

Guernsey answered 23/12, 2017 at 1:51 Comment(1)
It is equivalent to console.dir(obj, options)Obscenity

© 2022 - 2024 — McMap. All rights reserved.