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

2018-12-31 22:39发布

Is there a (Unix) shell script to format JSON in human-readable form?

Basically, I want it to transform the following:

{ "foo": "lorem", "bar": "ipsum" }

... into something like this:

{
    "foo": "lorem",
    "bar": "ipsum"
}

30条回答
不再属于我。
2楼-- · 2018-12-31 23:34

With Python 2.6+ you can just do:

echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool

or, if the JSON is in a file, you can do:

python -m json.tool my_json.json

if the JSON is from an internet source such as an API, you can use

curl http://my_url/ | python -m json.tool

For convenience in all of these cases you can make an alias:

alias prettyjson='python -m json.tool'

For even more convenience with a bit more typing to get it ready:

prettyjson_s() {
    echo "$1" | python -m json.tool
}

prettyjson_f() {
    python -m json.tool "$1"
}

prettyjson_w() {
    curl "$1" | python -m json.tool
}

for all the above cases. You can put this in .bashrc and it will be available every time in shell. Invoke it like prettyjson_s '{"foo": "lorem", "bar": "ipsum"}'.

查看更多
其实,你不懂
3楼-- · 2018-12-31 23:34

UPDATE I'm using jq now as suggested in another answer. It's extremely powerful at filtering JSON, but, at its most basic, also an awesome way to pretty print JSON for viewing.

jsonpp is a very nice command line JSON pretty printer.

From the README:

Pretty print web service responses like so:

curl -s -L http://<!---->t.co/tYTq5Pu | jsonpp

and make beautiful the files running around on your disk:

jsonpp data/long_malformed.json

If you're on Mac OS X, you can brew install jsonpp. If not, you can simply copy the binary to somewhere in your $PATH.

查看更多
人间绝色
4楼-- · 2018-12-31 23:36

If you use npm and Node.js, you can do npm install -g json and then pipe the command through json. Do json -h to get all the options. It can also pull out specific fields and colorize the output with -i.

curl -s http://search.twitter.com/search.json?q=node.js | json
查看更多
柔情千种
5楼-- · 2018-12-31 23:37

Simply pipe the output to jq ..

Example:

twurl -H ads-api.twitter.com '.......' | jq .
查看更多
步步皆殇っ
6楼-- · 2018-12-31 23:38

Try pjson. It has colors!

echo '{"json":"obj"} | pjson

Install it with pip:

⚡ pip install pjson

And then pipe any JSON content to pjson.

查看更多
柔情千种
7楼-- · 2018-12-31 23:40

That's how I do it:

curl yourUri | json_pp

It shortens the code and gets the job done.

查看更多
登录 后发表回答