Aksanth
Aksanth

Reputation: 319

Selecting in JQ with Contains in a Array

I want to select the particular item from the array using contains and get the first item using JQ.

JQ:

.amazon.items[] | select(.name | contains ("shoes")) 

JSON:

{
  "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"
      },{
        "id": 4,
        "name": "adidas shoes",
        "state": "in inventory"
      }
    ]
  }
} 

Expected Result:

{
  "activeitem": 2,
  "item": {
    "id": 2,
    "name": "adidas shoes",
    "state": "in inventory"
  }
}

Actual :

Tried various options like but not getting the Intended response .

  1. .amazon.items[] | select(.name | contains ("shoes"))
  2. .amazon.items | select(.[].name | contains ("shoes")) | .[0]

Also when I try to combine activeitem and item, I get something like this, which is also wrong.

{
  "activeitem": 2,
  "item": {
    "id": 2,
    "name": "adidas shoes",
    "state": "in inventory"
  }
},
  {
  "activeitem": 2,
  "item": {
    "id": 2,
    "name": "adidas shoes",
    "state": "in inventory"
  }
}

Upvotes: 4

Views: 2804

Answers (1)

peak
peak

Reputation: 116640

To edit "in-place" you could write:

.amazon
| .items |= map(select(.name | contains ("shoes")))[0]

If you really want to change the name 'items' to 'item', you could tweak the above as follows:

.amazon
| .item = (.items | map(select(.name | contains ("shoes")))[0])
| del(.items)

Upvotes: 4

Related Questions