You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 13:37:25