使用JQ从JSON输出中选择多个键和值

tyg4sfes  于 2023-10-21  发布在  其他
关注(0)|答案(3)|浏览(144)

我有一个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 'with_entriesjq select,但无法让它工作。

rt4zxlrg

rt4zxlrg1#

如果你想提供要保留的内容,你可以使用pick过滤器,如果你有jq 1.7:

map(pick(
  .iid, .project_id, .ref, .status, .source,
  .created_at, .updated_at, .web_url
))

Demo
如果你没有jq 1.7,你可以从源代码中复制它来定义它:

def pick(pathexps):
  . as $in | reduce path(pathexps) as $a (null;
      setpath($a; $in|getpath($a))
  );

map(pick(…))

Demo
如果你想提供要删除的内容,可以使用del

map(del(.id, .sha))

Demo
正如您尝试使用with_entriesselect一样,下面是如何使用这些过滤器实现所需结果的方法:
选择要保留的内容:

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

Demo
选择不保留的内容:

map(with_entries(select(.key | IN("id", "sha") | not)))

Demo
以上所有输出:

[
  {
    "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"
  }
]
rqenqsqc

rqenqsqc2#

您可以用途:

$ jq '[.[] | {iid: .iid, project_id: .project_id, ref: .ref, status: .status, source: .source, created_at: .created_at, updated_at: .updated_at, web_url: .web_url}]' file
[
  {
    "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"
  }
]
waxmsbnn

waxmsbnn3#

最简单的方法,适用于所有jq版本:

map({
  iid, project_id, ref, status, source,
  created_at, updated_at, web_url
})

Demo

相关问题