是否有(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'

其他回答

我就是这样做的:

curl yourUri | json_pp

它缩短了代码并完成了任务。

PHP版本,如果您有PHP>=5.4。

alias prettify_json=php -E '$o = json_decode($argn); print json_encode($o, JSON_PRETTY_PRINT);'
echo '{"a":1,"b":2}' | prettify_json

我用jshon来做你所描述的事情。只需运行:

echo $COMPACTED_JSON_TEXT | jshon

您还可以传递参数来转换JSON数据。

yq可以用于漂亮地打印JSON

echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json

它有一个定义缩进的选项

echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json --indent 3

您可以选择彩色和单色输出

echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json --colors
echo '{"foo": "lorem", "bar": "ipsum"}' | yq -o json --no-colors

使用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 ))"