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

后端 未结 30 2597
孤独总比滥情好
孤独总比滥情好 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:08

    a simple bash script for pretty json printing

    json_pretty.sh

    #/bin/bash
    
    grep -Eo '"[^"]*" *(: *([0-9]*|"[^"]*")[^{}\["]*|,)?|[^"\]\[\}\{]*|\{|\},?|\[|\],?|[0-9 ]*,?' | awk '{if ($0 ~ /^[}\]]/ ) offset-=4; printf "%*c%s\n", offset, " ", $0; if ($0 ~ /^[{\[]/) offset+=4}'
    

    Example:

    cat file.json | json_pretty.sh
    
    0 讨论(0)
  • 2020-11-22 17:11

    It is not too simple with a native way with the jq tools.

    For example:

    cat xxx | jq .
    
    0 讨论(0)
  • 2020-11-22 17:12

    If you use npm and Node.js, you can do npm install -g json and then pipe the command through json. Do json -h to get all the options. It can also pull out specific fields and colorize the output with -i.

    curl -s http://search.twitter.com/search.json?q=node.js | json
    
    0 讨论(0)
  • 2020-11-22 17:12

    Try pjson. It has colors!

    echo '{"json":"obj"} | pjson

    Install it with pip:

    ⚡ pip install pjson

    And then pipe any JSON content to pjson.

    0 讨论(0)
  • 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));\
     });\
    "
    
    0 讨论(0)
  • 2020-11-22 17:13

    Simply pipe the output to jq ..

    Example:

    twurl -H ads-api.twitter.com '.......' | jq .
    
    0 讨论(0)
提交回复
热议问题