pretty-print JSON using JavaScript

后端 未结 24 1681
一向
一向 2020-11-21 06:45

How can I display JSON in an easy-to-read (for human readers) format? I\'m looking primarily for indentation and whitespace, with perhaps even colors / font-styles / etc.

24条回答
  •  终归单人心
    2020-11-21 07:17

    Couldn't find any solution that had good syntax highlighting for the console, so here's my 2p

    Install & Add cli-highlight dependency

    npm install cli-highlight --save
    

    Define logjson globally

    const highlight = require('cli-highlight').highlight
    console.logjson = (obj) => console.log(
                                   highlight( JSON.stringify(obj, null, 4), 
                                              { language: 'json', ignoreIllegals: true } ));
    

    Use

    console.logjson({foo: "bar", someArray: ["string1", "string2"]});
    

提交回复
热议问题