How can I pretty-print JSON in a shell script?

后端 未结 30 2980
孤独总比滥情好
孤独总比滥情好 2020-11-22 16:27

Is there a (Unix) shell script to format JSON in human-readable form?

Basically, I want it to transform the following:

{ \"foo\": \"lorem\", \"bar\":         


        
30条回答
  •  执念已碎
    2020-11-22 17:13

    I use the "space" argument of JSON.stringify to pretty-print JSON in JavaScript.

    Examples:

    // Indent with 4 spaces
    JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, 4);
    
    // Indent with tabs
    JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, '\t');
    

    From the Unix command-line with Node.js, specifying JSON on the command line:

    $ node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, '\t'));" \
      '{"foo":"lorem","bar":"ipsum"}'
    

    Returns:

    {
        "foo": "lorem",
        "bar": "ipsum"
    }
    

    From the Unix command-line with Node.js, specifying a filename that contains JSON, and using an indent of four spaces:

    $ node -e "console.log(JSON.stringify(JSON.parse(require('fs') \
          .readFileSync(process.argv[1])), null, 4));"  filename.json
    

    Using a pipe:

    echo '{"foo": "lorem", "bar": "ipsum"}' | node -e \
    "\
     s=process.openStdin();\
     d=[];\
     s.on('data',function(c){\
       d.push(c);\
     });\
     s.on('end',function(){\
       console.log(JSON.stringify(JSON.parse(d.join('')),null,2));\
     });\
    "
    

提交回复
热议问题