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 .
.amazon.items[] |  select(.name | contains ("shoes")).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"
  }
}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With