是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
您可以简单地使用jq或json_pp等标准工具。
echo'{“foo”:“lorem”,“bar”:“ipsum”}'| json_pp
or
echo“{”foo“:”lorem“,”bar“:”ipsum“}”| jq
将像下面这样美化输出(jq甚至更丰富多彩):
{
"foo": "lorem",
"bar": "ipsum"
}
jq的巨大优势在于,如果您想解析和处理json,它可以做更多的工作。
其他回答
您可以简单地使用jq或json_pp等标准工具。
echo'{“foo”:“lorem”,“bar”:“ipsum”}'| json_pp
or
echo“{”foo“:”lorem“,”bar“:”ipsum“}”| jq
将像下面这样美化输出(jq甚至更丰富多彩):
{
"foo": "lorem",
"bar": "ipsum"
}
jq的巨大优势在于,如果您想解析和处理json,它可以做更多的工作。
我知道最初的帖子要求提供一个shell脚本,但有太多有用和不相关的答案,可能对原作者没有帮助。添加到不相关的内容:)
顺便说一下,我无法使用任何命令行工具。
如果有人想要简单的JSON JavaScript代码,他们可以这样做:
JSON.stringfy(JSON.parse(str), null, 4)
http://www.geospaces.org/geoweb/Wiki.jsp?page=JSON%20Utilities%20Demos
这里是JavaScript代码,它不仅美化了JSON,还按其属性或属性和级别对其进行排序。
如果输入是
{ "c": 1, "a": {"b1": 2, "a1":1 }, "b": 1},
它要么打印(将所有对象分组在一起):
{
"b": 1,
"c": 1,
"a": {
"a1": 1,
"b1": 2
}
}
OR(仅按键排序):
{
"a": {
"a1": 1,
"b1": 2
},
"b": 1,
"c": 1
}
PHP版本,如果您有PHP>=5.4。
alias prettify_json=php -E '$o = json_decode($argn); print json_encode($o, JSON_PRETTY_PRINT);'
echo '{"a":1,"b":2}' | prettify_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
$ echo '{ "foo": "lorem", "bar": "ipsum" }' \
> | python -c'import fileinput, json;
> print(json.dumps(json.loads("".join(fileinput.input())),
> sort_keys=True, indent=4))'
{
"bar": "ipsum",
"foo": "lorem"
}
注意:不是这样做的。
在Perl中也是如此:
$ cat json.txt \
> | perl -0007 -MJSON -nE'say to_json(from_json($_, {allow_nonref=>1}),
> {pretty=>1})'
{
"bar" : "ipsum",
"foo" : "lorem"
}
注2:如果你跑步
echo '{ "Düsseldorf": "lorem", "bar": "ipsum" }' \
| python -c'import fileinput, json;
print(json.dumps(json.loads("".join(fileinput.input())),
sort_keys=True, indent=4))'
可读性很好的单词将被编码
{
"D\u00fcsseldorf": "lorem",
"bar": "ipsum"
}
如果您的管道的其余部分将优雅地处理unicode,并且您希望JSON也是人性化的,那么只需使用ensure_ascii=False
echo '{ "Düsseldorf": "lorem", "bar": "ipsum" }' \
| python -c'import fileinput, json;
print json.dumps(json.loads("".join(fileinput.input())),
sort_keys=True, indent=4, ensure_ascii=False)'
你会得到:
{
"Düsseldorf": "lorem",
"bar": "ipsum"
}