如何在Linux中使用jq筛选JSON数组及指定属性内容?
使用jq提取JSON指定字段内容
输入JSON
{ "paging": { "count": 0, "total": 0, "offset": 0, "max": 0 }, "executions": [ { "id": 5, "href": "https://localhost.com.br", "permalink": "https://localhost.com.br", "status": "succeeded", "project": "PROJETO", "executionType": "scheduled", "date-started": { "unixtime": 1660793400012, "date": "2022-08-18T03:30:00Z" }, "date-ended": { "unixtime": 1660793409694, "date": "2022-08-18T03:30:09Z" }, "job": { "id": "cdkwednweoi-8745bjdf-kcjkjr8745", "averageDuration": 0, "name": "routine", "group": "", "project": "PROJECT", "description": "", "href": "https://localhost.com.br", "permalink": "https://localhost.com.br" }, "description": "runner", "argstring": null, "serverUUID": "jdnsdnasldnaje382nf5ubv", "successfulNodes": [ "84jsk937nf" ] } ] }
期望输出
"href": "https://localhost.com.br" "status": "succeeded" "project": "PROJETO" "date-started": "unixtime": 1660793400012, "date": "2022-08-18T03:30:00Z" "date-ended": "unixtime": 1660793409694, "date": "2022-08-18T03:30:09Z" "job": "name": "routine"
已尝试的命令
- 提取基础字段的有效命令:
jq -r '.executions[] | [.href, .status, .project]' - 无效的尝试:
jq '.executions[] | with_entries( select(.value | has("date-started") ) )'
解决方案
方案1:模拟期望的文本格式输出
直接针对性选择每个字段,通过字符串拼接实现你要的格式:
jq -r '.executions[] | "\"href\": \"\(.href)\"", "\"status\": \"\(.status)\"", "\"project\": \"\(.project)\"", "", "\"date-started\": ", " \"unixtime\": \(.date-started.unixtime),", " \"date\": \"\(.date-started.date)\"", "", "\"date-ended\": ", " \"unixtime\": \(.date-ended.unixtime),", " \"date\": \"\(.date-ended.date)\"", "", "\"job\":", " \"name\": \"\(.job.name)\"" '
.executions[]:遍历executions数组内的每个对象- 用字符串拼接生成目标格式,空字符串
""用来分隔不同区块实现换行
方案2:生成结构化JSON输出
如果可以接受标准JSON格式,可构建包含指定字段的新对象,输出更工整:
jq '.executions[] | { href, status, project, "date-started": ."date-started", "date-ended": ."date-ended", job: {name: .job.name} }'
输出结果:
{ "href": "https://localhost.com.br", "status": "succeeded", "project": "PROJETO", "date-started": { "unixtime": 1660793400012, "date": "2022-08-18T03:30:00Z" }, "date-ended": { "unixtime": 1660793409694, "date": "2022-08-18T03:30:09Z" }, "job": { "name": "routine" } }
内容的提问来源于stack exchange,提问作者anywhere
相关产品推荐
相关产品推荐

