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

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

    Thanks to J.F. Sebastian's very helpful pointers, here's a slightly enhanced script I've come up with:

    #!/usr/bin/python
    
    """
    Convert JSON data to human-readable form.
    
    Usage:
      prettyJSON.py inputFile [outputFile]
    """
    
    import sys
    import simplejson as json
    
    
    def main(args):
        try:
            if args[1] == '-':
                inputFile = sys.stdin
            else:
                inputFile = open(args[1])
            input = json.load(inputFile)
            inputFile.close()
        except IndexError:
            usage()
            return False
        if len(args) < 3:
            print json.dumps(input, sort_keys = False, indent = 4)
        else:
            outputFile = open(args[2], "w")
            json.dump(input, outputFile, sort_keys = False, indent = 4)
            outputFile.close()
        return True
    
    
    def usage():
        print __doc__
    
    
    if __name__ == "__main__":
        sys.exit(not main(sys.argv))
    
    0 讨论(0)
  • 2020-11-22 17:28
    1. brew install jq
    2. command + | jq
    3. (example: curl localhost:5000/blocks | jq)
    4. Enjoy!

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

    I wrote a tool that has one of the best "smart whitespace" formatters available. It produces more readable and less verbose output than most of the other options here.

    underscore-cli

    This is what "smart whitespace" looks like:

    I may be a bit biased, but it's an awesome tool for printing and manipulating JSON data from the command-line. It's super-friendly to use and has extensive command-line help/documentation. It's a Swiss Army knife that I use for 1001 different small tasks that would be surprisingly annoying to do any other way.

    Latest use-case: Chrome, Dev console, Network tab, export all as HAR file, "cat site.har | underscore select '.url' --outfmt text | grep mydomain"; now I have a chronologically ordered list of all URL fetches made during the loading of my company's site.

    Pretty printing is easy:

    underscore -i data.json print
    

    Same thing:

    cat data.json | underscore print
    

    Same thing, more explicit:

    cat data.json | underscore print --outfmt pretty
    

    This tool is my current passion project, so if you have any feature requests, there is a good chance I'll address them.

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

    I use jshon to do exactly what you're describing. Just run:

    echo $COMPACTED_JSON_TEXT | jshon
    

    You can also pass arguments to transform the JSON data.

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

    With Perl, if you install JSON::PP from CPAN you'll get the json_pp command. Stealing the example from B Bycroft you get:

    [pdurbin@beamish ~]$ echo '{"foo": "lorem", "bar": "ipsum"}' | json_pp
    {
       "bar" : "ipsum",
       "foo" : "lorem"
    }
    

    It's worth mentioning that json_pp comes pre-installed with Ubuntu 12.04 (at least) and Debian in /usr/bin/json_pp

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

    The JSON Ruby Gem is bundled with a shell script to prettify JSON:

    sudo gem install json
    echo '{ "foo": "bar" }' | prettify_json.rb
    

    Script download: gist.github.com/3738968

    0 讨论(0)
提交回复
热议问题