Aksanth
Aksanth

Reputation: 319

How to filter an array of objects based on value of a element in the Json in JQ

I am trying to get a value from the Json using JQ.

I have to get a ID from the inputJson , (activeItem) and use that ID to get the name of the element from list of items below.

Can this be done in single query ?

{
"amazon": {
"activeitem" : 2, 
"items": [
  {
    "id" : 1,
    "name": "harry potter",
    "state": "sold"
  },
  {
    "id" : 2,
    "name": "adidas shoes",
    "state": "in inventory"
  },
  {
    "id" : 3,
    "name": "watch",
    "state": "returned"
  }
]
}
}

Now i am getting the value first and the filtering, instead i want to do in single query.

Upvotes: 0

Views: 69

Answers (1)

peak
peak

Reputation: 117027

With your data, the filter:

.amazon
| .activeitem as $id
| .items[]
| select(.id == $id)
| .name

produces:

"adidas shoes"

(Use the -r command-line option if you want the raw string.)

Upvotes: 1

Related Questions