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

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

    That's how I do it:

    curl yourUri | json_pp
    

    It shortens the code and gets the job done.

    0 讨论(0)
  • 2020-11-22 17:23

    bat is a cat clone with syntax highlighting:

    Example:

    echo '{"bignum":1e1000}' | bat -p -l json
    

    -p will output without headers, and -l will explicitly specify the language.

    It has colouring and formatting for JSON and does not have the problems noted in this comment: How can I pretty-print JSON in a shell script?

    0 讨论(0)
  • 2020-11-22 17:23

    Install yajl-tools with the command below:

    sudo apt-get install yajl-tools
    

    then,

    echo '{"foo": "lorem", "bar": "ipsum"}' | json_reformat
    
    0 讨论(0)
  • 2020-11-22 17:24

    JSONLint has an open-source implementation on GitHub that can be used on the command line or included in a Node.js project.

    npm install jsonlint -g
    

    and then

    jsonlint -p myfile.json
    

    or

    curl -s "http://api.twitter.com/1/users/show/user.json" | jsonlint | less
    
    0 讨论(0)
  • 2020-11-22 17:25

    I recommend using the json_xs command line utility which is included in the JSON::XS perl module. JSON::XS is a Perl module for serializing/deserializing JSON, on a Debian or Ubuntu machine you can install it like this:

    sudo apt-get install libjson-xs-perl
    

    It is obviously also available on CPAN.

    To use it to format JSON obtained from a URL you can use curl or wget like this:

    $ curl -s http://page.that.serves.json.com/json/ | json_xs
    

    or this:

    $ wget -q -O - http://page.that.serves.json.com/json/ | json_xs
    

    and to format JSON contained in a file you can do this:

    $ json_xs < file-full-of.json
    

    To reformat as YAML, which some people consider to be more humanly-readable than JSON:

    $ json_xs -t yaml < file-full-of.json
    
    0 讨论(0)
  • 2020-11-22 17:26

    You can use: jq

    It's very simple to use and it works great! It can handle very large JSON structures, including streams. You can find their tutorials here.

    Usage examples:

    $ jq --color-output file1.json file1.json | less -R
    
    $ command_with_json_output | jq .
    
    $ jq # stdin/"interactive" mode, just enter some JSON
    
    $ jq <<< '{ "foo": "lorem", "bar": "ipsum" }'
    {
      "bar": "ipsum",
      "foo": "lorem"
    }
    

    Or use jq with identity filter:

    $ jq '.foo' <<< '{ "foo": "lorem", "bar": "ipsum" }'
    "lorem"
    
    0 讨论(0)
提交回复
热议问题