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

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

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

…变成这样:

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

当前回答

有TidyJSON。

它是C#,所以也许你可以让它用Mono编译,并使用*nix。但没有保证,抱歉。

其他回答

我就是这样做的:

curl yourUri | json_pp

它缩短了代码并完成了任务。

https://github.com/aidanmelen/json_pretty_print

from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division

import json
import jsonschema

def _validate(data):
    schema = {"$schema": "http://json-schema.org/draft-04/schema#"}
    try:
        jsonschema.validate(data, schema,
                            format_checker=jsonschema.FormatChecker())
    except jsonschema.exceptions.ValidationError as ve:
        sys.stderr.write("Whoops, the data you provided does not seem to be " \
        "valid JSON.\n{}".format(ve))

def pprint(data, python_obj=False, **kwargs):
    _validate(data)
    kwargs["indent"] = kwargs.get("indent", 4)
    pretty_data = json.dumps(data, **kwargs)
    if python_obj:
        print(pretty_data)
    else:
       repls = (("u'",'"'),
                ("'",'"'),
                ("None",'null'),
                ("True",'true'),
                ("False",'false'))
    print(reduce(lambda a, kv: a.replace(*kv), repls, pretty_data))

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

autocmd FileType json setlocal equalprg=json_reformat

多亏了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是最简单和最简单的。