是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
对于Node.js,您也可以使用“util”模块。它使用语法高亮显示、智能缩进、从键中删除引号,并使输出尽可能漂亮。
cat file.json | node -e "process.stdin.pipe(new require('stream').Writable({write: chunk => {console.log(require('util').inspect(JSON.parse(chunk), {depth: null, colors: true}))}}))"
其他回答
JSON Ruby Gem与一个shell脚本捆绑在一起,以美化JSON:
sudo gem install json
echo '{ "foo": "bar" }' | prettify_json.rb
脚本下载:gist.gitub.com/3738968
我使用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/.我认为这一个解析器比其他许多解析器更能容错。
如果使用npm和Node.js,则可以执行npm install-g json,然后通过json发送命令。执行json-h以获取所有选项。它还可以拉出特定字段,并用-i为输出着色。
curl -s http://search.twitter.com/search.json?q=node.js | json
如果你安装了Node.js,你可以用一行代码自己创建一个Node.js。创建一个漂亮的文件:
>vim漂亮
#!/usr/bin/env node
console.log(JSON.stringify(JSON.parse(process.argv[2]), null, 2));
添加执行权限:
>chmod+x漂亮> ./漂亮的“{”foo“:”lorem“,”bar“:”ipsum“}”
或者如果JSON在文件中:
#!/usr/bin/env node
console.log(JSON.stringify(require("./" + process.argv[2]), null, 2));
> ./漂亮的文件.json