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

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

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

…变成这样:

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

当前回答

同意jq。您可以将以下函数添加到$HOME/.bashrc中:

jqless () {
  args=$1
  shift
  jq --color-output . $args "$@" | less --raw-control-chars
}

这允许任意数量的输入JSON文件。

其他回答

尝试pjson。它有颜色!

使用pip安装:

⚡ pip安装pjson

然后将任何JSON内容通过管道传输到pjson。

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

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

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

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

sudo apt-get install yajl-tools

然后

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

对于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的“扩展系统”)。