pretty-print JSON using JavaScript

后端 未结 24 2257
一向
一向 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 06:59

    You can use console.dir(), which is a shortcut for console.log(util.inspect()). (The only difference is that it bypasses any custom inspect() function defined on an object.)

    It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets.

    const object = JSON.parse(jsonString)
    
    console.dir(object, {depth: null, colors: true})
    

    and for the command line:

    cat package.json | node -e "process.stdin.pipe(new stream.Writable({write: chunk => console.dir(JSON.parse(chunk), {depth: null, colors: true})}))"

提交回复
热议问题