是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
使用JavaScript/Node.js:看看vkBeautify.js插件,它为JSON和XML文本提供了漂亮的打印。
它是用纯JavaScript编写的,小于1.5KB(缩小),速度非常快。
其他回答
对于Perl,使用CPAN模块JSON::XS。它安装一个命令行工具json_xs。
验证:
json_xs -t null < myfile.json
将JSON文件src.JSON前置为pretty.JSON:
< src.json json_xs > pretty.json
如果没有json_x,请尝试json_pp。“pp”代表“纯perl”——该工具仅在perl中实现,没有绑定到外部C库(XS代表perl的“扩展系统”)。
当您的系统上安装了节点时,以下工作正常。
echo '{"test":1,"test2":2}' | npx json
{
"test": 1,
"test2": 2
}
多亏了J.F.Sebastian非常有用的指导,我想出了一个稍微增强的脚本:
#!/usr/bin/python
"""
Convert JSON data to human-readable form.
Usage:
prettyJSON.py inputFile [outputFile]
"""
import sys
import simplejson as json
def main(args):
try:
if args[1] == '-':
inputFile = sys.stdin
else:
inputFile = open(args[1])
input = json.load(inputFile)
inputFile.close()
except IndexError:
usage()
return False
if len(args) < 3:
print json.dumps(input, sort_keys = False, indent = 4)
else:
outputFile = open(args[2], "w")
json.dump(input, outputFile, sort_keys = False, indent = 4)
outputFile.close()
return True
def usage():
print __doc__
if __name__ == "__main__":
sys.exit(not main(sys.argv))
工具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