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:40

JSONLint has an open-source implementation on github can be used on the command line or included in a node.js project.

npm install jsonlint -g

and then

jsonlint -p myfile.json

or

curl -s "http://api.twitter.com/1/users/show/user.json" | jsonlint | less
查看更多
旧人旧事旧时光
3楼-- · 2018-12-31 23:40

Pygmentize

I combine Python's json.tool with pygmentize:

echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g

There are some alternatives to pygmentize which are listed in my this answer.

Here is a live demo:

Demo

查看更多
深知你不懂我心
4楼-- · 2018-12-31 23:42

The JSON Ruby Gem is bundled with a shell script to prettify JSON:

sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb

Script download: gist.github.com/3738968

查看更多
余生请多指教
5楼-- · 2018-12-31 23:42

I'm using httpie

$ pip install httpie

And you can use it like this

 $ http PUT localhost:8001/api/v1/ports/my 
 HTTP/1.1 200 OK
 Connection: keep-alive
 Content-Length: 93
 Content-Type: application/json
 Date: Fri, 06 Mar 2015 02:46:41 GMT
 Server: nginx/1.4.6 (Ubuntu)
 X-Powered-By: HHVM/3.5.1

 {
     "data": [], 
     "message": "Failed to manage ports in 'my'. Request body is empty", 
     "success": false
 }
查看更多
不再属于我。
6楼-- · 2018-12-31 23:44
  1. brew install jq
  2. command + | jq
  3. (example: curl localhost:5000/blocks | jq)
  4. Enjoy!

enter image description here

查看更多
笑指拈花
7楼-- · 2018-12-31 23:45

The PHP version, if you have PHP >= 5.4.

alias prettify_json=php -E '$o = json_decode($argn); print json_encode($o, JSON_PRETTY_PRINT);'
echo '{"a":1,"b":2}' | prettify_json
查看更多
登录 后发表回答