像 console.log 一样打印 JSON 会在 Node.js 中打印它

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

想知道是否可以像 Node.js 那样打印 JSON。如果有一些标准模块或其他东西可以做到这一点。

它有按键之间的间距,当它太长时它会换行等等。着色会是一个奖励。

JSON.stringify(object, null, 2) 漂亮地打印了 JSON,想知道是否还有其他隐藏的东西,或者任何标准,以便像 Node.js 那样做。谢谢。

这似乎可以通过使用 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 }));

选项对象采用一个名为 depth 的参数,该参数确定递归的深度。默认值是2。如果我把它增加到3:

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

我得到以下信息:

要使其无限递归传递depth: null。节点 cli 中的默认值似乎也是 2。