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

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

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

…变成这样:

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

当前回答

如果您想在控制台可视化json日志,可以使用munia漂亮的json

npm install -g munia-pretty-json

您的json数据(app-log.json)

{"time":"2021-06-09T02:50:22Z","level":"info","message":"Log for pretty JSON","module":"init","hostip":"192.168.0.138","pid":123}
{"time":"2021-06-09T03:27:43Z","level":"warn","message":"Here is warning message","module":"send-message","hostip":"192.168.0.138","pid":123}

运行命令:

munia-pretty-json app-log.json

下面是控制台上的可读输出:

您可以使用模板格式化输出。默认模板为“{time}{level-c}{{message}”

使用模板:

munia-pretty-json -t '{module -c} - {level} - {message}' app-log.json

输出:

其他回答

您可以使用此简单命令来实现以下结果:

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

有TidyJSON。

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

$ sudo apt-get install edit-json
$ prettify_json myfile.json

我正在使用httpie

$ pip install httpie

你可以这样使用

 $ http PUT localhost:8001/api/v1/ports/my 
 HTTP/1.1 200 OK
 Connection: keep-alive
 Content-Length: 93
 Content-Type: application/json
 Date: Fri, 06 Mar 2015 02:46:41 GMT
 Server: nginx/1.4.6 (Ubuntu)
 X-Powered-By: HHVM/3.5.1

 {
     "data": [], 
     "message": "Failed to manage ports in 'my'. Request body is empty", 
     "success": false
 }

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

echo $COMPACTED_JSON_TEXT | jshon

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