Reputation: 319
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"
}
}
Upvotes: 4
Views: 2804
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