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

如何用JQ从JSON中筛选指定键值对?已试with_entries/select未成功

使用jq筛选JSON中的指定键值对

输入JSON

[
  {
    "id": 4449282,
    "iid": 6316,
    "project_id": 1234,
    "sha": "abcdefg",
    "ref": "test_branch",
    "status": "running",
    "source": "web",
    "created_at": "2023-09-25T05:55:20.788Z",
    "updated_at": "2023-09-25T05:55:23.481Z",
    "web_url": "https://example.gitlab.com"
  }
]

期望输出

[
  {
    "iid": 6316,
    "project_id": 1234,
    "ref": "test_branch",
    "status": "running",
    "source": "web",
    "created_at": "2023-09-25T05:55:20.788Z",
    "updated_at": "2023-09-25T05:55:23.481Z",
    "web_url": "https://example.gitlab.com"
  }
]

可行的jq命令方案

方法1:明确保留目标键

直接指定需要保留的键列表,语法简洁高效:

jq 'map({iid, project_id, ref, status, source, created_at, updated_at, web_url})' input.json

map遍历数组内的每个对象,{key1, key2,...}语法会从原对象中提取指定键,生成仅包含这些键的新对象。

方法2:移除不需要的键

如果需要保留的键数量多,仅需删除少数冗余键(如本例的id和sha),可以用del命令:

jq 'map(del(.id, .sha))' input.json

map遍历数组,del(.key)删除对象中指定的键,剩余键值对即为目标结果。

方法3:用with_entries实现的正确写法

如果要通过with_entries结合select实现,需用IN函数匹配目标键名:

jq 'map(with_entries(select(.key | IN("iid", "project_id", "ref", "status", "source", "created_at", "updated_at", "web_url"))))' input.json

with_entries会根据select筛选后的键值对,重新构建符合要求的对象。

内容的提问来源于stack exchange,提问作者Meenakshisundaram Ramanathan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 21:17:43