是否有(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";'
其他回答
我写了一个工具,它有一个最好的“智能空白”格式器。与这里的大多数其他选项相比,它生成的输出可读性更高,详细程度更低。
下划线cli
这就是“智能空白”的样子:
我可能有点偏见,但它是一个很棒的工具,可以从命令行打印和处理JSON数据。它使用起来超级友好,并且有大量的命令行帮助/文档。这是一把瑞士军刀,我用它来完成1001项不同的小任务,如果用其他方式来做,那会令人惊讶地讨厌。
最新用例:Chrome、开发人员控制台、网络选项卡,全部导出为HAR文件,“cat site.HAR |下划线select‘.url’--outmt text|grep mydomain”;现在,我有一个按时间顺序排列的列表,列出了在加载公司网站期间获取的所有URL。
漂亮的打印很容易:
underscore -i data.json print
同样的事情:
cat data.json | underscore print
同样的事情,更明确:
cat data.json | underscore print --outfmt pretty
这个工具是我目前的激情项目,所以如果你有任何功能需求,我很有机会解决它们。
JSONLint在GitHub上有一个开源实现,可以在命令行上使用,也可以包含在Node.js项目中。
npm install jsonlint -g
然后
jsonlint -p myfile.json
or
curl -s "http://api.twitter.com/1/users/show/user.json" | jsonlint | less
我使用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));\
});\
"
我的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/.我认为这一个解析器比其他许多解析器更能容错。
我建议使用json::XSperl模块中包含的json_xs命令行实用程序。JSON::XS是一个Perl模块,用于序列化/反序列化JSON,在Debian或Ubuntu机器上可以这样安装:
sudo apt-get install libjson-xs-perl
它显然也可以在CPAN上使用。
要使用它格式化从URL获得的JSON,可以使用curl或wget,如下所示:
$ curl -s http://page.that.serves.json.com/json/ | json_xs
或者:
$ wget -q -O - http://page.that.serves.json.com/json/ | json_xs
要格式化文件中包含的JSON,可以执行以下操作:
$ json_xs < file-full-of.json
要重新格式化为YAML,有些人认为它比JSON更具可读性:
$ json_xs -t yaml < file-full-of.json