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.
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.
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 }));
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:
To make it recurse indefinitely pass depth: null
. The default value seems to be 2 in the node cli as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With