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

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

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

…变成这样:

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

当前回答

尝试pjson。它有颜色!

使用pip安装:

⚡ pip安装pjson

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

其他回答

根据我的经验,雅杰很好。我使用它的json_reformat命令在vim中漂亮地打印.json文件,方法是在我的.vimrc中放置以下行:

autocmd FileType json setlocal equalprg=json_reformat

我是json liner的作者。这是一个命令行工具,用于将JSON转换为grep友好格式。试试看。

$ echo '{"a": 1, "b": 2}' | json-liner
/%a 1
/%b 2
$ echo '["foo", "bar", "baz"]' | json-liner
/@0 foo
/@1 bar
/@2 baz

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

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

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

使用Node.js的单线解决方案如下所示:

$ node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"

例如:

$ cat test.json | node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"