user375868
user375868

Reputation: 1378

How to get the first object after filtering an array in jq?

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

Answers (3)

ikegami
ikegami

Reputation: 385916

jq -r 'first( .tags[] | select(.key=="env") ).value'

jqplay


.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

Inian
Inian

Reputation: 85683

Use first(expr) to provide an expression that satisfies your usecase.

first(.tags[]? | select(.key == "env") .value)

Upvotes: 3

Mukesh Soni
Mukesh Soni

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

Related Questions