是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
是否有(Unix)shell脚本将JSON格式化为可读格式?
基本上,我希望它转换以下内容:
{ "foo": "lorem", "bar": "ipsum" }
…变成这样:
{
"foo": "lorem",
"bar": "ipsum"
}
当前回答
有TidyJSON。
它是C#,所以也许你可以让它用Mono编译,并使用*nix。但没有保证,抱歉。
其他回答
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));\
});\
"
下面是Groovy的一行代码:
echo '{"foo": "lorem", "bar": "ipsum"}' | groovy -e 'import groovy.json.*; println JsonOutput.prettyPrint(System.in.text)'
尝试pjson。它有颜色!
使用pip安装:
⚡ pip安装pjson
然后将任何JSON内容通过管道传输到pjson。
工具ydump是一个JSON漂亮的打印机:
$ ydump my_data.json
{
"foo": "lorem",
"bar": "ipsum"
}
或者可以通过管道输入JSON:
$ echo '{"foo": "lorem", "bar": "ipsum"}' | ydump
{
"foo": "lorem",
"bar": "ipsum"
}
这可能是除了使用jq工具之外最短的解决方案。
该工具是OCaml的yojson库的一部分,并在此处进行了说明。
在Debian及其衍生产品上,libyojson-ocml-dev包包含此工具。或者,可以通过OPAM安装yojson。