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

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

提交回复
热议问题