首页 文章

如何在shell脚本中打印JSON?

提问于
浏览
2610

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

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

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

...进入这样的事情:

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

30 回答

  • 171

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

    autocmd FileType json setlocal equalprg=json_reformat
    
  • 731

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

    jj -p # for reading from STDIN
    

    要么

    jj -p -i input.json
    

    它(2018)仍然很新,所以也许它不会按照你期望的方式处理无效的JSON,但它很容易在主要平台上安装 .

  • 39

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

    例:

    twurl -H ads-api.twitter.com '.......' | jq .
    
  • 28
    $ 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"
    }
    
  • 326

    如果使用npm和Node.js,则可以执行 npm install -g json ,然后通过 json 传递命令 . 请 json -h 获取所有选项 . 它还可以拉出特定字段并使用 -i 将输出着色 .

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

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

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

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

  • 11

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

    gem install jazor
    jazor --help
    
  • 51

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

    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
    

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

  • 36

    我通常只做:

    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
    
  • 9

    这就是我这样做的方式:

    curl yourUri | json_pp
    

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

  • 53

    JSONLintopen-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
    
  • 3882

    使用the jq tools的原生方式并不太简单 .

    例如:

    cat xxx | jq .
    
  • 64

    UPDATE 我正在使用 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 中的某个位置即可 .

  • 8

    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
    
  • 67

    或者,使用Ruby:

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

    在* 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)
    

    把它放在一个文件中(我在_90291的答案之后将其命名为"prettyJSON")在你的PATH和 chmod +x 中它,你很高兴 .

  • 364

    Pygmentize

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

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

    pygmentize有一些替代品,列在my this answer中 .

    这是一个现场演示:

  • 41

    你可以使用:jq

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

    这是一个例子:

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

    或者换句话说:

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

    感谢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))
    
  • 19

    我正在使用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
     }
    
  • 18

    试试pjson . 它有颜色!

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

    pip 安装:

    ⚡ pip install pjson

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

  • 29

    Vanilla Bash

    一个简单的Bash脚本( grep / awk ),用于漂亮的JSON打印,没有第三方安装:

    json_pretty.sh

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

    示例:

    1)在控制台中读取文件和漂亮的打印

    cat file.json | json_pretty.sh
    

    2)使用Windows GIT Bash从文件到文件(基于UTF8):

    cat fileIn.json |sh.exe json_pretty.sh > fileOut.json
    
  • 38

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

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

  • 15

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

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

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

  • 37

    我使用jshon完全按照你所描述的那样做 . 赶紧跑:

    echo $COMPACTED_JSON_TEXT | jshon
    

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

  • 67

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

    sudo apt-get install yajl-tools

    然后,

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

  • 18

    我使用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');
    

    从带有nodejs的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));\
     });\
    "
    
  • 11

    使用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"适用于"pure perl" - 该工具仅在Perl中实现,没有绑定到外部C库(这是XS代表的,Perl的"Extension System") .

  • 10
    • brew install jq

    • command + | jq

    • (例如: curl localhost:5000/blocks | jq

    • 享受!

相关问题