是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
使用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
其他回答
多亏了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))
只需将输出通过管道发送到jq。。
例子:
twurl -H ads-api.twitter.com '.......' | jq .
J.F.Sebastian的解决方案在Ubuntu 8.04中不适用。下面是一个经过修改的Perl版本,可以与旧的1.X JSON库一起使用:
perl -0007 -MJSON -ne 'print objToJson(jsonToObj($_, {allow_nonref=>1}), {pretty=>1}), "\n";'
使
我将Python的json工具与pygmentize相结合:
echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g
我的回答中列出了一些pygmentize的替代方案。
这里是一个现场演示:
使用以下命令安装yajl工具:
sudo apt-get install yajl-tools
然后
echo '{"foo": "lorem", "bar": "ipsum"}' | json_reformat