Reputation: 17997
I'm trying to filter an array of objects by their name
property, and then select the first element that passed the filter.
I've read How to filter array of objects by element property values using jq? and I've been experimenting with jq and https://jqplay.org/ for the past 2h but I don't get it.
The whole thing is a bash script executed within github actions.
Where ALL_ZEIT_DEPLOYMENTS
is:
{
"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"
}
]
}
And the bash script is:
# 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
With the following jq
filter .deployments[] | select(.name == "nrn-v2-mst-aptd-gcms-lcz-sty-c1") | .url
executed at https://jqplay.org/ I get a "list" of urls.
But, I don't understand how I extract the first element of this, it's not an array and even if I try to convert it into an array with .deployments[] | select(.name == "nrn-v2-mst-aptd-gcms-lcz-sty-c1") | [.url] | .[0]
I still get the same result.
What am I missing?
My goal is to make it work within Github Actions.
I'm using the web editor to test things out beforehand. Also, I'd like to split the different part of the processing into different variables so that they're printed out in the Github Actions logs because it'll help debug faster. (e.g: filter array, then select first element)
Solution:
first(.deployments[] | select(.name == "nrn-v2-mst-aptd-gcms-lcz-sty-c1") | .url)
Upvotes: 1
Views: 911
Reputation: 116780
I get a "list" of urls.
That “list” is actually a stream of JSON values, so you could simply enclose your jq expression in first( )
to get the first value. Please see the jq manual for further details.
Another possibility would to use map
instead of itemizing the array with []
, but using first
as above would be more efficient.
Upvotes: 1