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

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

    On *nix, reading from stdin and writing to stdout works better:

    #!/usr/bin/env python
    """
    Convert JSON data to human-readable form.
    
    (Reads from stdin and writes to stdout)
    """
    
    import sys
    try:
        import simplejson as json
    except:
        import json
    
    print json.dumps(json.loads(sys.stdin.read()), indent=4)
    sys.exit(0)
    

    Put this in a file (I named mine "prettyJSON" after AnC's answer) in your PATH and chmod +x it, and you're good to go.

提交回复
热议问题