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

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

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

…变成这样:

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

当前回答

我使用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));\
 });\
"

其他回答

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

echo $COMPACTED_JSON_TEXT | jshon

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

使用Python 2.6+,您可以做到:

echo '{"foo": "lorem", "bar": "ipsum"}' | python -m json.tool

或者,如果JSON在文件中,则可以执行以下操作:

python -m json.tool my_json.json

如果JSON来自互联网源(如API),则可以使用

curl http://my_url/ | python -m json.tool

在所有这些情况下,为了方便起见,您可以使用别名:

alias prettyjson='python -m json.tool'

为了更方便,只需多输入一点即可:

prettyjson_s() {
    echo "$1" | python -m json.tool
}

prettyjson_f() {
    python -m json.tool "$1"
}

prettyjson_w() {
    curl "$1" | python -m json.tool
}

对于所有上述情况。你可以把它放在.bashrc中,它将在shell中随时可用。像prettyjson_s‘{“foo”:“lorem”,“bar”:“ipsum”}‘一样调用它。

请注意,正如@pnd在下面的注释中指出的,在Python 3.5+中,JSON对象在默认情况下不再排序。要排序,请在末尾添加--sort-keys标志。即…|python-mjson.tool——排序键。

有TidyJSON。

它是C#,所以也许你可以让它用Mono编译,并使用*nix。但没有保证,抱歉。

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

该方法还“检测HTTP响应/标头,打印它们,并跳过主体(用于'curl-i')”。

使

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

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

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

这里是一个现场演示: