是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
使用JavaScript/Node.js:看看vkBeautify.js插件,它为JSON和XML文本提供了漂亮的打印。
它是用纯JavaScript编写的,小于1.5KB(缩小),速度非常快。
其他回答
看看Jazor。这是一个用Ruby编写的简单命令行JSON解析器。
gem install jazor
jazor --help
或者,使用Ruby:
echo '{ "foo": "lorem", "bar": "ipsum" }' | ruby -r json -e 'jj JSON.parse gets'
使
我将Python的json工具与pygmentize相结合:
echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g
我的回答中列出了一些pygmentize的替代方案。
这里是一个现场演示:
您可以简单地使用jq或json_pp等标准工具。
echo'{“foo”:“lorem”,“bar”:“ipsum”}'| json_pp
or
echo“{”foo“:”lorem“,”bar“:”ipsum“}”| jq
将像下面这样美化输出(jq甚至更丰富多彩):
{
"foo": "lorem",
"bar": "ipsum"
}
jq的巨大优势在于,如果您想解析和处理json,它可以做更多的工作。
我使用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));\
});\
"