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

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

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

…变成这样:

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

当前回答

$ sudo apt-get install edit-json
$ prettify_json myfile.json

其他回答

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

我是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

如果你安装了Node.js,你可以用一行代码自己创建一个Node.js。创建一个漂亮的文件:

>vim漂亮

#!/usr/bin/env node

console.log(JSON.stringify(JSON.parse(process.argv[2]), null, 2));

添加执行权限:

>chmod+x漂亮> ./漂亮的“{”foo“:”lorem“,”bar“:”ipsum“}”

或者如果JSON在文件中:

#!/usr/bin/env node

console.log(JSON.stringify(require("./" + process.argv[2]), null, 2));

> ./漂亮的文件.json

使用Python 2.6+,您可以做到:

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

或者,如果JSON在文件中,则可以执行以下操作:

python -m json.tool my_json.json

如果JSON来自互联网源(如API),则可以使用

curl http://my_url/ | python -m json.tool

在所有这些情况下,为了方便起见,您可以使用别名:

alias prettyjson='python -m json.tool'

为了更方便,只需多输入一点即可:

prettyjson_s() {
    echo "$1" | python -m json.tool
}

prettyjson_f() {
    python -m json.tool "$1"
}

prettyjson_w() {
    curl "$1" | python -m json.tool
}

对于所有上述情况。你可以把它放在.bashrc中,它将在shell中随时可用。像prettyjson_s‘{“foo”:“lorem”,“bar”:“ipsum”}‘一样调用它。

请注意,正如@pnd在下面的注释中指出的,在Python 3.5+中,JSON对象在默认情况下不再排序。要排序,请在末尾添加--sort-keys标志。即…|python-mjson.tool——排序键。

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