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

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

    I usually just do:

    echo '{"test":1,"test2":2}' | python -mjson.tool
    

    And to retrieve select data (in this case, "test"'s value):

    echo '{"test":1,"test2":2}' | python -c 'import sys,json;data=json.loads(sys.stdin.read()); print data["test"]'
    

    If the JSON data is in a file:

    python -mjson.tool filename.json
    

    If you want to do it all in one go with curl on the command line using an authentication token:

    curl -X GET -H "Authorization: Token wef4fwef54te4t5teerdfgghrtgdg53" http://testsite/api/ | python -mjson.tool
    

提交回复
热议问题