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

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

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

…变成这样:

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

当前回答

你也可以选择使用在线工具。

我发现http://jsonprettyprint.net是最简单和最简单的。

其他回答

J.F.Sebastian的解决方案在Ubuntu 8.04中不适用。下面是一个经过修改的Perl版本,可以与旧的1.X JSON库一起使用:

perl -0007 -MJSON -ne 'print objToJson(jsonToObj($_, {allow_nonref=>1}), {pretty=>1}), "\n";'

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

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

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

从自述文件:

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

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

bat是一个cat克隆,语法突出显示:

例子:

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

-p将不带头输出,-l将显式指定语言。

它具有JSON的颜色和格式,没有本评论中提到的问题:如何在shell脚本中漂亮地打印JSON?

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