(unix)shell脚本中如何漂亮地打印JSON?

有一个(unix)shell脚本来以可读的forms格式化JSON吗?

基本上,我想要它改变以下内容:

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

…变成这样的东西:

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

使用Python 2.6+,你可以这样做:

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

或者,如果JSON在文件中,则可以执行以下操作:

 python -m json.tool my_json.json 

如果JSON来自诸如API等互联网源,则可以使用

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

为了方便在所有这些情况下,你可以做一个别名:

 alias prettyjson='python -m json.tool' 

为了获得更多的便利,还需要打字:

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

对于所有上述情况。 你可以把它放在.bashrc并且每次都可以在shell中使用。 调用它像prettyjson_s '{"foo": "lorem", "bar": "ipsum"}'

你可以使用: jq

使用起来非常简单,而且效果很好! 它可以处理非常大的JSON结构,包括stream。 你可以在这里find他们的教程。

这里是一个例子:

 $ jq . <<< '{ "foo": "lorem", "bar": "ipsum" }' { "bar": "ipsum", "foo": "lorem" } 

换句话说:

 $ echo '{ "foo": "lorem", "bar": "ipsum" }' | jq . { "bar": "ipsum", "foo": "lorem" } 

我使用JSON.stringify的“空间”参数在JavaScript中漂亮地打印JSON。

例子:

 // Indent with 4 spaces JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, 4); // Indent with tabs JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, '\t'); 

在Unix命令行中使用nodejs,在命令行上指定json:

 $ node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, '\t'));" \ '{"foo":"lorem","bar":"ipsum"}' 

返回:

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

从Unix命令行和nodejs中,指定一个包含json的文件名,并使用4个空格的缩进:

 $ node -e "console.log(JSON.stringify(JSON.parse(require('fs') \ .readFileSync(process.argv[1])), null, 4));" filename.json 

使用pipe道:

 echo '{"foo": "lorem", "bar": "ipsum"}' | node -e \ "\ s=process.openStdin();\ d=[];\ s.on('data',function(c){\ d.push(c);\ });\ s.on('end',function(){\ console.log(JSON.stringify(JSON.parse(d.join('')),null,2));\ });\ " 

我写了一个具有最好的“智能空白”格式化工具之一的工具。 它比这里的大多数其他选项产生更可读和更less的详细输出。

强调-CLI

这就是“智能空白”的样子:

我可能有点偏见,但它是从命令行打印和操纵JSON数据的一个很棒的工具。 它使用起来非常友好,并有丰富的命令行帮助/文档。 这是瑞士军刀,我用1001个不同的小任务,这将是令人吃惊的做任何其他方式。 最新的使用案例:Chrome,开发者控制台,networking标签,导出所有HAR文件,“cat site.har |下划线select'.url'–outfmt text | grep mydomain”; 现在我有一个按照时间顺序列出的所有url提取在我的comany的网站加载。

漂亮的打印很容易:

 underscore -i data.json print 

一样:

 cat data.json | underscore print 

同样的事情,更明确:

 cat data.json | underscore print --outfmt pretty 

这个工具是我目前的激情项目,所以如果你有任何function要求,我很好的机会解决他们。

我通常只是做

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

并检索select的数据(在这种情况下“testing”的价值):

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

如果json数据在文件中:

 python -mjson.tool filename.json 

如果你想用curl在命令行上使用auth令牌来完成这一切

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

感谢JF Sebastian的非常有帮助的指针,这是一个稍微增强的脚本,我想出了:

 #!/usr/bin/python """ Convert JSON data to human-readable form. Usage: prettyJSON.py inputFile [outputFile] """ import sys import simplejson as json def main(args): try: if args[1] == '-': inputFile = sys.stdin else: inputFile = open(args[1]) input = json.load(inputFile) inputFile.close() except IndexError: usage() return False if len(args) < 3: print json.dumps(input, sort_keys = False, indent = 4) else: outputFile = open(args[2], "w") json.dump(input, outputFile, sort_keys = False, indent = 4) outputFile.close() return True def usage(): print __doc__ if __name__ == "__main__": sys.exit(not main(sys.argv)) 

JSON Ruby Gem捆绑了一个shell脚本来优化JSON:

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

脚本下载: gist.github.com/3738968

使用Perl,使用CPAN模块JSON::XS 。 它安装一个命令行工具json_xs

validation:

 json_xs -t null < myfile.json 

src.json JSON文件src.jsonpretty.json

 < src.json json_xs > pretty.json 

如果您没有json_xs ,请尝试json_pp 。 “pp”是“pure perl” – 这个工具只用Perl实现,没有绑定到外部C库(这就是XS代表的Perl扩展系统)。

在* nix上,从标准input读取并写入标准输出效果更好:

 #!/usr/bin/env python """ Convert JSON data to human-readable form. (Reads from stdin and writes to stdout) """ import sys try: import simplejson as json except: import json print json.dumps(json.loads(sys.stdin.read()), indent=4) sys.exit(0) 

把它放在一个文件中(在AnC的回答后,我把它命名为“prettyJSON”)在你的PATH和chmod +x ,你就可以走了。

如果您使用npm和nodejs,您可以执行npm install -g json ,然后通过jsonpipe道命令。 做json -h来获得所有的选项。 它也可以拉出特定的字段并用-i对输出着色。

 curl -s http://search.twitter.com/search.json?q=node.js | json 

更新我正在使用jq现在在另一个答案build议。 它过滤JSONfunction非常强大,但是在最基本的方面,也是一个非常好的方式来打印JSON以供查看。

jsonpp是一个非常漂亮的命令行JSON漂亮的打印机。

从自述文件:

漂亮的打印Web服务响应如下所示:

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

并使您的磁盘上运行的文件变得美丽:

 jsonpp data/long_malformed.json 

如果你在Mac OS X上,你可以brew install jsonpp 。 如果没有,您可以简单地将二进制文件复制到$PATH某处

尝试pjson 。 它有颜色!

echo“{”json“:”obj“} | pjson

pip安装它:

⚡ pip install pjson

然后,将任何json内容pipe道到pjson

我使用jshon – 完全按照你所描述的,运行:

  echo $COMPACTED_JSON_TEXT | jshon 

您也可以传递参数来转换json数据。

 $ 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" } 

注意:这不是做这件事的方法。

在Perl中是一样的:

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

注2:如果你运行

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

很好的可读的单词变成\ u编码

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

如果您的pipe道的其余部分将优雅地处理unicode,并且您希望您的JSON也是人性化的,只需使用 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)' 

你会得到:

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

看看贾佐尔 。 这是一个用Ruby编写的简单的命令行JSONparsing器。

 gem install jazor jazor --help 

或者,用Ruby:

 echo '{ "foo": "lorem", "bar": "ipsum" }' | ruby -r json -e 'jj JSON.parse gets' 

只需输出到jq .

例:

 twurl -H ads-api.twitter.com '.......' | jq . 

JSONLint 在github上有一个开源的实现,可以在命令行上使用或者包含在node.js项目中。

 npm install jsonlint -g 

接着

 jsonlint -p myfile.json 

要么

 curl -s "http://api.twitter.com/1/users/show/user.json" | jsonlint | less 

用jq工具的本地方式是否太简单了 – https://stedolan.github.io/jq/tutorial/

例如: cat xxx | jq . cat xxx | jq .

我build议使用包含在JSON :: XS perl模块中的json_xs命令行实用程序。 JSON :: XS是用于序列化/反序列化JSON的perl模块,在Debian或Ubuntu机器上,您可以像这样安装它:

 sudo apt-get install libjson-xs-perl 

它显然也可以在cpan上得到 。

要使用它来格式化从url中获得的json,你可以使用curl或wget像这样:

 $ curl -s http://page.that.serves.json.com/json/ | json_xs 

或这个:

 $ wget -q -O - http://page.that.serves.json.com/json/ | json_xs 

并格式化包含在文件中的json,你可以这样做:

 $ json_xs < file-full-of.json 

要重新格式化为YAML,有人认为它比JSON更具人性化可读性:

 $ json_xs -t yaml < file-full-of.json 

有了Perl,如果你从CPAN安装JSON :: PP ,你会得到json_pp命令。 从B Bycroft偷你的例子 :

 [pdurbin@beamish ~]$ echo '{"foo": "lorem", "bar": "ipsum"}' | json_pp { "bar" : "ipsum", "foo" : "lorem" } 

值得一提的是, json_pp预装了Ubuntu 12.04(至less)和Debian /usr/bin/json_pp

Pygmentize

我结合python json.tool与pygmentize

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

pygmentize有一些替代scheme列在我的这个答案 。

这里是一个现场演示:

演示

  1. brew install jq
  2. command + | jq
  3. (例如: curl localhost:5000/blocks | jq
  4. 请享用!

在这里输入图像描述

用下面的命令安装yajl-tools:

sudo apt-get install yajl-tools

然后,

echo '{"foo": "lorem", "bar": "ipsum"}' | json_reformat

yajl非常好,以我的经验。 我使用它的json_reformat命令在vim通过在我的.vimrc放入以下行来漂亮地打印json_reformat文件:

 autocmd FileType json setlocal equalprg=json_reformat 

我正在使用httpie

 $ pip install httpie 

你可以像这样使用它

  $ 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 } 

我就是这样做的:

 curl yourUri | json_pp 

简短的代码,并完成工作。

PHP版本,如果你有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 

我知道这个问题已经回复了,但我想logging一个比Json的美化命令更好的Ruby解决scheme,gem colorful_json是相当不错的。

 gem install colorful_json echo '{"foo": "lorem", "bar": "ipsum"}' | cjson { "foo": "lorem", "bar": "ipsum" } 

工具ydump是一个JSON漂亮的打印机:

 $ ydump my_data.json { "foo": "lorem", "bar": "ipsum" } 

或者你可以在JSON中pipe道:

 $ echo '{"foo": "lorem", "bar": "ipsum"}' | ydump { "foo": "lorem", "bar": "ipsum" } 

除了使用jq工具,这可能是最短的解决scheme。

这个工具是OCaml的yojson库的一部分,在这里有logging。

在Debian和衍生产品上, libyojson-ocaml-dev软件包包含了这个工具。 或者, yojson可以通过OPAM安装。