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

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

    $ echo '{ "foo": "lorem", "bar": "ipsum" }' \
    > | python -c'import fileinput, json;
    > print(json.dumps(json.loads("".join(fileinput.input())),
    >                  sort_keys=True, indent=4))'
    {
        "bar": "ipsum",
        "foo": "lorem"
    }
    

    NOTE: It is not the way to do it.

    The same in Perl:

    $ cat json.txt \
    > | perl -0007 -MJSON -nE'say to_json(from_json($_, {allow_nonref=>1}), 
    >                                     {pretty=>1})'
    {
       "bar" : "ipsum",
       "foo" : "lorem"
    }
    

    Note 2: If you run

    echo '{ "Düsseldorf": "lorem", "bar": "ipsum" }' \
    | python -c'import fileinput, json;
    print(json.dumps(json.loads("".join(fileinput.input())),
                     sort_keys=True, indent=4))'
    

    the nicely readable word becomes \u encoded

    {
        "D\u00fcsseldorf": "lorem", 
        "bar": "ipsum"
    }
    

    If the remainder of your pipeline will gracefully handle unicode and you'd like your JSON to also be human-friendly, simply use ensure_ascii=False

    echo '{ "Düsseldorf": "lorem", "bar": "ipsum" }' \
    | python -c'import fileinput, json;
    print json.dumps(json.loads("".join(fileinput.input())),
                     sort_keys=True, indent=4, ensure_ascii=False)'
    

    and you'll get:

    {
        "Düsseldorf": "lorem", 
        "bar": "ipsum"
    }
    

提交回复
热议问题