是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
brew安装jq命令+|jq(示例:curl localhost:5000/blocks|jq)享受
其他回答
如果使用npm和Node.js,则可以执行npm install-g json,然后通过json发送命令。执行json-h以获取所有选项。它还可以拉出特定字段,并用-i为输出着色。
curl -s http://search.twitter.com/search.json?q=node.js | json
bat是一个cat克隆,语法突出显示:
例子:
echo '{"bignum":1e1000}' | bat -p -l json
-p将不带头输出,-l将显式指定语言。
它具有JSON的颜色和格式,没有本评论中提到的问题:如何在shell脚本中漂亮地打印JSON?
多亏了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))
使用Perl,如果您从CPAN安装JSON::PP,您将获得JSON_PP命令。从B Bycroft那里偷了一个例子,你会得到:
[pdurbin@beamish ~]$ echo '{"foo": "lorem", "bar": "ipsum"}' | json_pp
{
"bar" : "ipsum",
"foo" : "lorem"
}
值得一提的是,json_pap预装了Ubuntu 12.04(至少)和/usr/bin/json_pap中的Debian
在*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”)中,就可以开始了。