Reputation: 1378
Given the following JSON
{
"tags": [
{
"key": "env",
"value": "foo"
},
{
"key": "env",
"value": "bar"
}
]
}
I am trying to find out the first tag where the key is env
. I have this-
.tags[] | select (.key=="env") |.[0]
but that gives me an error Cannot index object with number
Upvotes: 3
Views: 1035
Reputation: 385916
jq -r 'first( .tags[] | select(.key=="env") ).value'
.tags[]
flattens the array into a stream of values. You're applying .[0]
to each of the values, not a filtered array. To filter an array, you'd use
.tags | map(select(...)) | .[0]
or
.tags | map(select(...)) | first
map(...)
is a shorthand for [ .[] | ... ]
, so the above is equivalent to
.tags | [ .[] | select(...) ] | first
and
[ .tags[] | select(...) ] | first
Finally, [ ... ] | first
can be written as first(...)
.
first( .tags[] | select(...) )
Upvotes: 0
Reputation: 85683
Use first(expr)
to provide an expression that satisfies your usecase.
first(.tags[]? | select(.key == "env") .value)
Upvotes: 3
Reputation: 6668
You could wrap the results of your query in an array and then pick the first one
[.tags[] | select(.key=="env")] | .[0]
Upvotes: 0