是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
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))
其他回答
更新我现在使用jq,正如另一个答案中所建议的。它在过滤JSON方面非常强大,但最基本的是,它也是一种漂亮的打印JSON以供查看的绝佳方式。
jsonpp是一个非常好的命令行JSON漂亮的打印机。
从自述文件:
漂亮的打印web服务响应如下:curl-s-L http://<!---->t.co/tYTq5Pu|jsonpp并使磁盘上运行的文件变得漂亮:jsonpp数据/long_malformed.json
如果您使用的是Mac OS X,则可以酝酿安装jsonpp。如果没有,您可以简单地将二进制文件复制到$PATH中的某个位置。
jj速度极快,可以经济地处理巨大的JSON文档,不干扰有效的JSON数字,并且易于使用,例如。
jj -p # for reading from STDIN
or
jj -p -i input.json
它(2018)仍然很新,所以它可能不会像您期望的那样处理无效的JSON,但它很容易安装在主要平台上。
我建议使用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
JSON Ruby Gem与一个shell脚本捆绑在一起,以美化JSON:
sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb
脚本下载:gist.gitub.com/3738968
下面是Groovy的一行代码:
echo '{"foo": "lorem", "bar": "ipsum"}' | groovy -e 'import groovy.json.*; println JsonOutput.prettyPrint(System.in.text)'