如何通过元素属性值过滤对象数组并使用jq选择第一个元素?

时间:2020-10-17 13:08:26

标签: json select stream jq github-actions

我试图通过对象的name属性来过滤对象数组,然后选择通过过滤器的第一个元素。

在过去的2小时里,我已经读过How to filter array of objects by element property values using jq?,并且一直在尝试使用jq和https://jqplay.org/,但我听不懂。

整个过程都是在github动作中执行的bash脚本。

ALL_ZEIT_DEPLOYMENTS在哪里:

{
    "deployments":[
        {
            "uid":"dpl_95kYvsWHaq3yAuJJ6uAaWXQY287R",
            "name":"nrn-v2-mst-aptd-gcms-lcz-sty-c1",
            "url":"nrn-v2-mst-aptd-gcms-lcz-sty-c1-n9ru06e1q.vercel.app"
        },
        {
            "uid":"dpl_Fwk5UXLJFU1miLnSfoUM91gnqSNK",
            "name":"nrn-v2-mst-aptd-gcms-lcz-sty-c2",
            "url":"nrn-v2-mst-aptd-gcms-lcz-sty-c2-hpbca7bei.vercel.app"
        },
        {
            "uid":"dpl_5U9vDaGKWBkSJF1H1EYMzreWeYvu",
            "name":"nrn-v2-mst-aptd-gcms-lcz-sty-c1",
            "url":"nrn-v2-mst-aptd-gcms-lcz-sty-c1-16g58d4zd.vercel.app"
        }
    ]
}

bash脚本是:

  # Filter deployments by their "name" property in order to consider only deployments related to the current project
  ZEIT_LATEST_DEPLOYMENT_FOR_CURRENT_PROJECT=`echo $ALL_ZEIT_DEPLOYMENTS | jq '.deployments[] | select(.name == "$VERCEL_PROJECT_NAME")  | .url'`
  echo "Latest Vercel deployment for current project: " $ZEIT_LATEST_DEPLOYMENT_FOR_CURRENT_PROJECT

  # Extract the first element (which is the latest vercel deployment), and strip the double quotes from its value
  ZEIT_LATEST_DEPLOYMENT_DOMAIN_FOR_CURRENT_PROJECT=`echo $ZEIT_LATEST_DEPLOYMENT_FOR_CURRENT_PROJECT | jq --raw-output '[].url'`
  echo "Latest Vercel deployment domain url for current project: " $ZEIT_LATEST_DEPLOYMENT_DOMAIN_FOR_CURRENT_PROJECT

https://jqplay.org/执行以下jq过滤器.deployments[] | select(.name == "nrn-v2-mst-aptd-gcms-lcz-sty-c1") | .url后,我得到了一个“列表”网址。

enter image description here

但是,我不明白如何提取其中的第一个元素,它不是数组,即使我尝试使用.deployments[] | select(.name == "nrn-v2-mst-aptd-gcms-lcz-sty-c1") | [.url] | .[0]将其转换为数组,我仍然会得到相同的结果。

enter image description here

我想念什么?

我的目标是使其在Github Actions中运行。

我正在使用Web编辑器预先测试事物。另外,我想将处理的不同部分分为不同的变量,以便将它们打印在Github Actions日志中,因为它可以帮助加快调试速度。 (例如:过滤器数组,然后选择第一个元素)


解决方案:

first(.deployments[] | select(.name == "nrn-v2-mst-aptd-gcms-lcz-sty-c1") | .url)

enter image description here

1 个答案:

答案 0 :(得分:1)

我得到了网址的“列表”。

该“列表”实际上是JSON值的,因此您只需将jq表达式括在first( )中即可获得第一个值。有关更多详细信息,请参见jq手册。

另一种可能性是使用map而不是用[]逐项列出数组,但是如上所述使用first会更有效率。