过滤数组中包含子字符串的元素

问题描述 投票:0回答:1

我有这个数据集

{
  "imageDetails": [
    {
      "registryId": "259611133533",
      "repositoryName": "core",
      "imageDigest": "sha256:b17e3f35ff2e0b9af437372d7777e1cc092994eb87dbddf2d73d467eb122cf51",
      "imageTags": [
        "master-202404300732"
      ],
      "imageSizeInBytes": 470904068,
      "imagePushedAt": "2024-04-30T09:34:19+02:00",
      "imageManifestMediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "artifactMediaType": "application/vnd.docker.container.image.v1+json"
    },
    {
      "registryId": "259611133533",
      "repositoryName": "core",
      "imageDigest": "sha256:dfe2a1df2d6d8b39bdd37887979f027de29f802295e1b7536c31ac786fc0bbea",
      "imageTags": [
        "develop-202404230503"
      ],
      "imageSizeInBytes": 471216957,
      "imagePushedAt": "2024-04-23T07:07:14+02:00",
      "imageManifestMediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "artifactMediaType": "application/vnd.docker.container.image.v1+json",
      "lastRecordedPullTime": "2024-04-24T08:55:56.071000+02:00"
    },
    {
      "registryId": "259611133533",
      "repositoryName": "core",
      "imageDigest": "sha256:39239ba86a543aa6787da0a02479d6f59eb00742e4810a9d4b52f1423a5e0392",
      "imageTags": [
        "master-202404260911"
      ],
      "imageSizeInBytes": 470843809,
      "imagePushedAt": "2024-04-26T11:12:51+02:00",
      "imageManifestMediaType": "application/vnd.docker.distribution.manifest.v2+json",
      "artifactMediaType": "application/vnd.docker.container.image.v1+json",
      "lastRecordedPullTime": "2024-04-26T11:14:06.695000+02:00"
    }
  ]
}

我想按

imagePushedAt
imageTags
过滤数据集,其中应包含字符串
master

我测试过以下内容

imageDetails[?imagePushedAt<`2024-04-27` && imageDetails.contains(@, `master`)]

但是,不幸的是这不起作用。
在某种程度上,我通过使用这个查询得到了我想要的东西

imageDetails[?imagePushedAt < `2024-04-27`] | [].imageTags[?contains(@,`master`)]

但是,当

imageTags
不匹配时,此解决方案返回一个空数组,而不是过滤掉结果。

jmespath
1个回答
0
投票

由于

imageTags
是一个数组,所以
imageTags.contains(@, `master`)
意味着您想要在
master
数组中严格等于
imageTags
的元素,而您的意思是 “对于数组的每个元素,我想要该元素(s) 确实包含
master
"
.

后者可以通过

表示
imageTags[?contains(@, `master`)]

因为,虽然

@
应用于数组时代表数组的一个元素,但这里它被 作为过滤器应用于数组的每个元素,因此
@
现在代表
imageTags 的每个字符串
数组。

所以,你的整个查询最终是:

imageDetails[?
  imagePushedAt < `2024-04-27` 
  && imageTags[?contains(@, `master`)]
]

在您的示例 JSON 中,这将产生单个元素:

[
  {
    "registryId": "259611133533",
    "repositoryName": "core",
    "imageDigest": "sha256:39239ba86a543aa6787da0a02479d6f59eb00742e4810a9d4b52f1423a5e0392",
    "imageTags": [
      "master-202404260911"
    ],
    "imageSizeInBytes": 470843809,
    "imagePushedAt": "2024-04-26T11:12:51+02:00",
    "imageManifestMediaType": "application/vnd.docker.distribution.manifest.v2+json",
    "artifactMediaType": "application/vnd.docker.container.image.v1+json",
    "lastRecordedPullTime": "2024-04-26T11:14:06.695000+02:00"
  }
]
© www.soinside.com 2019 - 2024. All rights reserved.