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

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

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

…变成这样:

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

当前回答

我建议使用json::XSperl模块中包含的json_xs命令行实用程序。JSON::XS是一个Perl模块,用于序列化/反序列化JSON,在Debian或Ubuntu机器上可以这样安装:

sudo apt-get install libjson-xs-perl

它显然也可以在CPAN上使用。

要使用它格式化从URL获得的JSON,可以使用curl或wget,如下所示:

$ curl -s http://page.that.serves.json.com/json/ | json_xs

或者:

$ wget -q -O - http://page.that.serves.json.com/json/ | json_xs

要格式化文件中包含的JSON,可以执行以下操作:

$ json_xs < file-full-of.json

要重新格式化为YAML,有些人认为它比JSON更具可读性:

$ json_xs -t yaml < file-full-of.json

其他回答

在*nix上,从stdin读取和写入stdout效果更好:

#!/usr/bin/env python
"""
Convert JSON data to human-readable form.

(Reads from stdin and writes to stdout)
"""

import sys
try:
    import simplejson as json
except:
    import json

print json.dumps(json.loads(sys.stdin.read()), indent=4)
sys.exit(0)

把这个放在PATH和chmod+x-it中的一个文件(我用AnC的答案命名我的“prettyJSON”)中,就可以开始了。

我建议使用json::XSperl模块中包含的json_xs命令行实用程序。JSON::XS是一个Perl模块,用于序列化/反序列化JSON,在Debian或Ubuntu机器上可以这样安装:

sudo apt-get install libjson-xs-perl

它显然也可以在CPAN上使用。

要使用它格式化从URL获得的JSON,可以使用curl或wget,如下所示:

$ curl -s http://page.that.serves.json.com/json/ | json_xs

或者:

$ wget -q -O - http://page.that.serves.json.com/json/ | json_xs

要格式化文件中包含的JSON,可以执行以下操作:

$ json_xs < file-full-of.json

要重新格式化为YAML,有些人认为它比JSON更具可读性:

$ json_xs -t yaml < file-full-of.json

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

看看Jazor。这是一个用Ruby编写的简单命令行JSON解析器。

gem install jazor
jazor --help

TL;DR:对于性能,请使用jj-p<my.json。

基准

我在这里采取了一些解决方案,并用下一个虚拟脚本对它们进行了基准测试:

function bench {
    time (
      for i in {1..1000}; do
        echo '{ "foo" : { "bar": { "dolorem" : "ipsum", "quia" : { "dolor" : "sit"} } } }' \
        | $@ > /dev/null
      done
    )
}

这是我的mac(32 GB,苹果M1 Max,YMMV)上的结果:

bench python -m json.tool
# 8.39s user 12.31s system 42% cpu 48.536 total
bench jq
# 13.12s user 1.28s system 87% cpu 16.535 total
bench bat -p -l json # NOTE: only syntax colorisation.
# 1.87s user 1.47s system 66% cpu 5.024 total
bench jj -p
# 1.94s user 2.44s system 57% cpu 7.591 total
bench xidel -s - -e '$json' --printed-json-format=pretty                      
# 4.32s user 1.89s system 76% cpu 8.101 total

感谢@peak和您对jj发现的回答!