如何在shell脚本中打印JSON?

问题描述 投票:2731回答:54

是否有(Unix)shell脚本以人类可读的形式格式化JSON?

基本上,我希望它改变以下内容:

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

...进入这样的事情:

{
    "foo": "lorem",
    "bar": "ipsum"
}
json unix command-line format pretty-print
54个回答
4105
投票

使用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"}'一样调用它。


68
投票

在* nix上,从stdin读取并写入stdout效果更好:

#!/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中,你很高兴。


64
投票

JSON Ruby Gem与shell脚本捆绑在一起以美化JSON:

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

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


55
投票

更新我现在正在使用jq,如另一个答案所示。它在过滤JSON方面非常强大,但从最基本的角度来看,它也是一种非常棒的方式来打印JSON以供查看。

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

来自README:

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

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

并使磁盘上运行的文件变得漂亮:

jsonpp data/long_malformed.json

如果您使用的是Mac OS X,则可以使用brew install jsonpp。如果没有,您只需将二进制文件复制到$PATH中的某个位置即可。


51
投票

试试pjson。它有颜色!

pip安装它:

⚡ pip install pjson

然后将任何JSON内容传递给pjson


49
投票

这就是我这样做的方式:

curl yourUri | json_pp

它缩短了代码并完成了工作。


42
投票
$ 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"
}

如果您的管道的其余部分将优雅地处理unicode并且您希望您的JSON也是人性化的,那么简单地说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)'

你会得到:

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

39
投票

我使用jshon来完成您所描述的内容。赶紧跑:

echo $COMPACTED_JSON_TEXT | jshon

您还可以传递参数以转换JSON数据。


37
投票

或者,使用Ruby:

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

36
投票

看看Jazor。这是一个用Ruby编写的简单命令行JSON解析器。

gem install jazor
jazor --help

32
投票

一个简单的bash脚本,用于漂亮的json打印

JSON_pretty.是

#/bin/bash

grep -Eo '"[^"]*" *(: *([0-9]*|"[^"]*")[^{}\["]*|,)?|[^"\]\[\}\{]*|\{|\},?|\[|\],?|[0-9 ]*,?' | awk '{if ($0 ~ /^[}\]]/ ) offset-=4; printf "%*c%s\n", offset, " ", $0; if ($0 ~ /^[{\[]/) offset+=4}'

例:

cat file.json | json_pretty.sh

828
投票

你可以使用:jq

它使用起来非常简单,效果很好!它可以处理非常大的JSON结构,包括流。你可以找到他们的教程here

这是一个例子:

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

或者换句话说:

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

30
投票

JSONLint有一个open-source implementation on GitHub,可以在命令行上使用或包含在Node.js项目中。

npm install jsonlint -g

然后

jsonlint -p myfile.json

要么

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

29
投票

只需将输出管道输出到jq .即可。

例:

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

24
投票

Pygmentize

我将Python json.tool与pygments结合起来:

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

my this answer中列出了pygmentize的一些替代品。

这是一个现场演示:

Demo


19
投票

使用Perl,如果从CPAN安装JSON::PP,您将获得json_pp命令。从example窃取B Bycroft你得到:

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

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


19
投票

我建议使用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

18
投票

您可以使用此简单命令来实现结果:

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

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

enter image description here


15
投票

jj超级快,可以经济地处理巨大的JSON文档,不会弄乱有效的JSON数字,并且易于使用,例如

jj -p # for reading from STDIN

要么

jj -p -i input.json

它(2018)仍然很新,所以也许它不会像你期望的那样处理无效的JSON,但它很容易在主要平台上安装。


12
投票

bat是一个cat克隆,语法高亮:

例:

echo '{"bignum":1e1000}' | bat -p -l json

-p将输出不带标题,-l将明确指定语言。

它具有JSON的着色和格式,并且没有此评论中提到的问题:How can I pretty-print JSON in a shell script?


11
投票

使用以下命令安装yajl-tools:

sudo apt-get install yajl-tools

然后,

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


367
投票

我使用JSON.stringify的“space”参数在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');

从带有Node.js的Unix命令行,在命令行上指定JSON:

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

返回:

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

从带有Node.js的Unix命令行,指定包含JSON的文件名,并使用四个空格的缩进:

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

使用管道:

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));\
 });\
"

10
投票

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

autocmd FileType json setlocal equalprg=json_reformat

329
投票

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

underscore-cli

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

我可能有点偏颇,但它是一个很棒的工具,用于从命令行打印和操作JSON数据。它使用起来非常友好,并提供广泛的命令行帮助/文档。这是一把瑞士军刀,我用它来完成1001个不同的小任务,以任何其他方式令人惊讶地烦人。

最新用例:Chrome,开发控制台,网络选项卡,全部导出为HAR文件,“cat site.har |下划线选择'.url' - outfmt text | grep mydomain”;现在我有一个按时间顺序列出的所有URL提取列表,在加载我公司的网站时。

漂亮的打印很简单:

underscore -i data.json print

一样:

cat data.json | underscore print

同样的事情,更明确:

cat data.json | underscore print --outfmt pretty

这个工具是我目前的激情项目,所以如果您有任何功能请求,我很有可能会解决它们。


171
投票

我通常只做:

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

并检索选择数据(在这种情况下,“测试”的值):

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一次性完成所有操作:

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

85
投票

感谢J.F. 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))

73
投票

如果你使用npm和Node.js,你可以做npm install -g json,然后通过json管道命令。做json -h得到所有的选择。它还可以拉出特定字段并使用-i为输出着色。

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

73
投票

使用the jq tools本土方式并不简单。

例如:

cat xxx | jq .

68
投票

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

验证:

json_xs -t null < myfile.json

将JSON文件src.json整理为pretty.json

< src.json json_xs > pretty.json

如果你没有json_xs,试试json_pp。 “pp”用于“纯perl” - 该工具仅在Perl中实现,没有绑定到外部C库(这是XS代表的,Perl的“扩展系统”)。

© www.soinside.com 2019 - 2024. All rights reserved.