是否有(Unix)shell脚本将JSON格式化为可读格式?

基本上,我希望它转换以下内容:

{ "foo": "lorem", "bar": "ipsum" }

…变成这样:

{
    "foo": "lorem",
    "bar": "ipsum"
}

当前回答

或者,使用Ruby:

echo '{ "foo": "lorem", "bar": "ipsum" }' | ruby -r json -e 'jj JSON.parse gets'

其他回答

如果你安装了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

我是json liner的作者。这是一个命令行工具,用于将JSON转换为grep友好格式。试试看。

$ echo '{"a": 1, "b": 2}' | json-liner
/%a 1
/%b 2
$ echo '["foo", "bar", "baz"]' | json-liner
/@0 foo
/@1 bar
/@2 baz

使用Node.js的单线解决方案如下所示:

$ node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"

例如:

$ cat test.json | node -e "console.log( JSON.stringify( JSON.parse(require('fs').readFileSync(0) ), 0, 1 ))"

这里有一个比Json的pretify命令更好的Ruby解决方案。gem colorful_json相当不错。

gem install colorful_json
echo '{"foo": "lorem", "bar": "ipsum"}' | cjson
{
  "foo": "lorem",
  "bar": "ipsum"
}

使

我将Python的json工具与pygmentize相结合:

echo '{"foo": "bar"}' | python -m json.tool | pygmentize -g

我的回答中列出了一些pygmentize的替代方案。

这里是一个现场演示: