在 Node 的 REPL/Interactive 模式下漂亮打印 JSON

Pretty Print JSON in Node's REPL/Interactive Mode

通过从命令行输入命令 nodenode will start a REPL。在这个 REPL 中,有没有办法漂亮地打印 JSON?

例如: 来自 Bash:

Now using node v12.14.1 (npm v6.13.6)
:~/Code/tmp$ node

启动 REPL:

Welcome to Node.js v12.14.1.
Type ".help" for more information.
> msg =  { "hello":"world", "quantity": 1 }

执行 JSON.stringify(msg) 产生:

'{"hello":"world","quantity":1}'

执行 JSON.stringify(msg, null, 2) 产生:

'{\n  "hello": "world",\n  "quantity": 1\n}'

我想要的是:

{
  "hello": "world",
  "quantity": 1
}

JSON.stringify returns 未解释到节点控制台的字符串。

如果要解释字符串,请使用 console.log(JSON.stringify(msg, null, 2)) .

注意console.log显示的是一个字符串,不再解释数据(数字上的颜色是黄色,绿色对于字符串 ...)