技术解析

请教下如何提取 curl 格式化输出的值
0
2021-06-29 07:30:30
idczone
如题 :想把 curl 得到的值按照自己想要的格式输出到文本,方便监控
curl 输出的值:
{"success":true,"data":{"request_5xx":1,"traffic_write":10866877,"average_traffix_write":426.43633010242,"average_traffic_read":429.33143664404,"traffic_read":10940653,"average_request_time":0.44471063102306,"total_count":25483,"request_3xx":0,"request_2xx":23981,"request_4xx":1501,"total_request_time":11332.561010361}
想得到的格式:
traffic_write:10866877
request_4xx:1501
echo '{"success":true,"data":{"request_5xx":1,"traffic_write":10866877,"average_traffix_write":426.43633010242,"average_traffic_read":429.33143664404,"traffic_read":10940653,"average_request_time":0.44471063102306,"total_count":25483,"request_3xx":0,"request_2xx":23981,"request_4xx":1501,"total_request_time":11332.561010361}}' | jq '. | {traffic_write: .data.traffic_write, request_4xx: .data.request_4xx}'

把 echo '{"success":true,"data":{"request_5xx":1,"traffic_write":10866877,"average_traffix_write":426.43633010242,"average_traffic_read":429.33143664404,"traffic_read":10940653,"average_request_time":0.44471063102306,"total_count":25483,"request_3xx":0,"request_2xx":23981,"request_4xx":1501,"total_request_time":11332.561010361}}' 换成 curl xxxx 即可

yum install jq
https://stedolan.github.io/jq/manual/
jq 比较好用。下面是一个例子:
https://jqplay.org/s/vsOpssDUO_

嗯,这个工具确实蛮好用的,之前也在用,想请教下 我格式化出来的 带逗号,这个如何在获取参数的时候取消掉?
比如 :cat page.txt |jq .|grep request_4xx| cut -d ":" -f 2 得到的值 :1505, 想取消掉逗号

试试 `jq --raw-output`

用 jq 直接取字段,不要用 grep 处理。1 楼的答案。 比如 jq ".data.request_4xx"

话说直接用命令行下的 tr 和 grep 就行了啊,不需要安装额外的工具:
echo '{"request_5xx":1,"traffic_write":10866877,"average_traffix_write":426.43633010242,"average_traffic_read":429.33143664404,"traffic_read":10940653,"average_request_time":0.44471063102306,"total_count":25483,"request_3xx":0,"request_2xx":23981,"request_4xx":1501,"total_request_time":11332.561010361}' | tr -d '"' | grep -oP '(traffic_write:\d+)|(request_4xx:\d+)'

感谢

哈哈,不知道我格式有问题还是 ,得到的数据有点问题

谢谢大牛,这个办法真直接!

再请教下,生成的数据都在一行。如果要达到换行的效果,\n 应该加在那里呢?

```
echo '{"success":true,"data":{"request_5xx":1,"traffic_write":10866877,"average_traffix_write":426.43633010242,"average_traffic_read":429.33143664404,"traffic_read":10940653,"average_request_time":0.44471063102306,"total_count":25483,"request_3xx":0,"request_2xx":23981,"request_4xx":1501,"total_request_time":11332.561010361}}' | python -mjson.tool
```

输出成 json 或者 xml 就可以了,都是数据存储格式,会自动调整的

显示成一行了?我这里显示的是两行啊,你是要把两行变成一行?还是一行变成两行?反正这两种都可以通过 sed 实现。
两行内容变成一行:
echo 'traffic_write:10866877\nrequest_4xx:1501' | sed 'N;s/\n/\t/g'
一行内容变成两行:
echo 'traffic_write:10866877\trequest_4xx:1501' | sed 's/\s\+/\n/g'
把对应的 sed 命令继续用管道接在之前的命令后面就行了。

好,谢谢!

数据地带为您的网站提供全球顶级IDC资源
在线咨询
专属客服