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

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

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

…变成这样:

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

当前回答

你可以用西德尔。

Xidel是一个命令行工具,可以使用CSS、XPath 3.0、XQuery 3.0、JSONiq或模式模板从HTML/XML页面或JSON API下载和提取数据。它还可以创建新的或转换的XML/HTML/JSON文档。

默认情况下,Xidel漂亮打印:

$ xidel -se '$json' <<< '{"foo":"lorem","bar":"ipsum"}'
{
  "foo": "lorem",
  "bar": "ipsum"
}

or:

$ echo '{"foo":"lorem","bar":"ipsum"}' | xidel -se '$json'
{
  "foo": "lorem",
  "bar": "ipsum"
}

其他回答

使用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 ))"

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))

下面是Groovy的一行代码:

echo '{"foo": "lorem", "bar": "ipsum"}' | groovy -e 'import groovy.json.*; println JsonOutput.prettyPrint(System.in.text)'
$ sudo apt-get install edit-json
$ prettify_json myfile.json

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