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

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

提交回复
热议问题