是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
J.F.Sebastian的解决方案在Ubuntu 8.04中不适用。下面是一个经过修改的Perl版本,可以与旧的1.X JSON库一起使用:
perl -0007 -MJSON -ne 'print objToJson(jsonToObj($_, {allow_nonref=>1}), {pretty=>1}), "\n";'
其他回答
在*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”)中,就可以开始了。
我的JSON文件没有被这些方法解析。
我的问题类似于帖子“Google数据源JSON无效吗?”?。
那篇帖子的答案帮助我找到了解决方案。
它被认为是没有字符串键的无效JSON。
{id:'name',label:'Name',type:'string'}
必须是:
{"id": "name", "label": "Name", "type": "string"}
此链接对一些不同的JSON解析器进行了很好的全面比较:http://deron.meranda.us/python/comparing_json_modules/basic
这让我http://deron.meranda.us/python/demjson/.我认为这一个解析器比其他许多解析器更能容错。
多亏了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。您可以将以下函数添加到$HOME/.bashrc中:
jqless () {
args=$1
shift
jq --color-output . $args "$@" | less --raw-control-chars
}
这允许任意数量的输入JSON文件。
使用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