是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
使用以下命令安装yajl工具:
sudo apt-get install yajl-tools
然后
echo '{"foo": "lorem", "bar": "ipsum"}' | json_reformat
其他回答
有TidyJSON。
它是C#,所以也许你可以让它用Mono编译,并使用*nix。但没有保证,抱歉。
我使用JSON.stringify的“space”参数在JavaScript中漂亮地打印JSON。
示例:
// Indent with 4 spaces
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, 4);
// Indent with tabs
JSON.stringify({"foo":"lorem","bar":"ipsum"}, null, '\t');
在带有Node.js的Unix命令行中,在命令行中指定JSON:
$ node -e "console.log(JSON.stringify(JSON.parse(process.argv[1]), null, '\t'));" \
'{"foo":"lorem","bar":"ipsum"}'
退货:
{
"foo": "lorem",
"bar": "ipsum"
}
从带有Node.js的Unix命令行,指定包含JSON的文件名,并使用四个空格的缩进:
$ node -e "console.log(JSON.stringify(JSON.parse(require('fs') \
.readFileSync(process.argv[1])), null, 4));" filename.json
使用管道:
echo '{"foo": "lorem", "bar": "ipsum"}' | node -e \
"\
s=process.openStdin();\
d=[];\
s.on('data',function(c){\
d.push(c);\
});\
s.on('end',function(){\
console.log(JSON.stringify(JSON.parse(d.join('')),null,2));\
});\
"
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))
工具ydump是一个JSON漂亮的打印机:
$ ydump my_data.json
{
"foo": "lorem",
"bar": "ipsum"
}
或者可以通过管道输入JSON:
$ echo '{"foo": "lorem", "bar": "ipsum"}' | ydump
{
"foo": "lorem",
"bar": "ipsum"
}
这可能是除了使用jq工具之外最短的解决方案。
该工具是OCaml的yojson库的一部分,并在此处进行了说明。
在Debian及其衍生产品上,libyojson-ocml-dev包包含此工具。或者,可以通过OPAM安装yojson。
在一行中使用Ruby:
echo '{"test":1,"test2":2}' | ruby -e "require 'json'; puts JSON.pretty_generate(JSON.parse(STDIN.read))"
您可以为此设置别名:
alias to_j="ruby -e \"require 'json';puts JSON.pretty_generate(JSON.parse(STDIN.read))\""
然后你可以更方便地使用它
echo '{"test":1,"test2":2}' | to_j
{
"test": 1,
"test2": 2
}
如果你想用颜色显示JSON,你可以安装awesome_print,
gem install awesome_print
then
alias to_j="ruby -e \"require 'json';require 'awesome_print';ap JSON.parse(STDIN.read)\""
试试看!
echo '{"test":1,"test2":2, "arr":["aa","bb","cc"] }' | to_j