使用jq命令行格式化json

我经常使用curl命令在命令行进行http调试,而现在的接口一般都是Restful形式,所以在命令行下面格式化json会是一个很常见的需求。
我使用的是jq这个开源软件。

jq is a lightweight and flexible command-line JSON processor.

使用示例

如下的使用方式,返回的json串并不会被格式化

~ » curl -XPOST http://4e28ea4de04c4d36b02ef03b8a010963-cn-beijing.gateway.xxx.cloud:8081/__/httpProxy/post
{"timestamp":1519810716048,"status":400,"error":"Bad Request","exception":"org.springframework.http.converter.HttpMessageNotReadableException","message":"Required request body is missing: public org.springframework.web.context.request.async.DeferredResult<org.springframework.http.ResponseEntity<java.lang.String>> com.xxx.tc.qcloudgateway.executor.controller.ExecutorController.execWithRequestBody(java.lang.String,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)","path":"/__/httpProxy/post"}

而使用jq进行json格式化则很简单

~ » curl -XPOST http://4e28ea4de04c4d36b02ef03b8a010963-cn-beijing.gateway.xxx.cloud:8081/__/httpProxy/post | jq .
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   525    0   525    0     0  42321      0 --:--:-- --:--:-- --:--:-- 43750
{
  "timestamp": 1519810727373,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.http.converter.HttpMessageNotReadableException",
  "message": "Required request body is missing: public org.springframework.web.context.request.async.DeferredResult<org.springframework.http.ResponseEntity<java.lang.String>> com.xxx.tc.qcloudgateway.executor.controller.ExecutorController.execWithRequestBody(java.lang.String,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)",
  "path": "/__/httpProxy/post"
}

如果你绝的上面的那一串“% Total % Received % Xferd Average Speed Time Time Time Current”碍眼,那么可以给curl命令增加-s选项:

~ » curl -s -XPOST http://4e28ea4de04c4d36b02ef03b8a010963-cn-beijing.gateway.xxx.cloud:8081/__/httpProxy/post | jq .
{
  "timestamp": 1519810733479,
  "status": 400,
  "error": "Bad Request",
  "exception": "org.springframework.http.converter.HttpMessageNotReadableException",
  "message": "Required request body is missing: public org.springframework.web.context.request.async.DeferredResult<org.springframework.http.ResponseEntity<java.lang.String>> com.xxx.tc.qcloudgateway.executor.controller.ExecutorController.execWithRequestBody(java.lang.String,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)",
  "path": "/__/httpProxy/post"
}
本文版权归作者所有,禁止一切形式的转载,复制等操作
赞赏

微信赞赏支付宝赞赏

发表评论

电子邮件地址不会被公开。 必填项已用*标注