是否有(Unix)shell脚本将JSON格式化为可读格式?

基本上,我希望它转换以下内容:

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

…变成这样:

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

当前回答

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

验证:

json_xs -t null < myfile.json

将JSON文件src.JSON前置为pretty.JSON:

< src.json json_xs > pretty.json

如果没有json_x,请尝试json_pp。“pp”代表“纯perl”——该工具仅在perl中实现,没有绑定到外部C库(XS代表perl的“扩展系统”)。

其他回答

使用以下命令安装yajl工具:

sudo apt-get install yajl-tools

然后

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

更新我现在使用jq,正如另一个答案中所建议的。它在过滤JSON方面非常强大,但最基本的是,它也是一种漂亮的打印JSON以供查看的绝佳方式。

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

从自述文件:

漂亮的打印web服务响应如下:curl-s-L http://<!---->t.co/tYTq5Pu|jsonpp并使磁盘上运行的文件变得漂亮:jsonpp数据/long_malformed.json

如果您使用的是Mac OS X,则可以酝酿安装jsonpp。如果没有,您可以简单地将二进制文件复制到$PATH中的某个位置。

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

多亏了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))

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

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

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