xpt
xpt

Reputation: 22994

Array filtering with jq on sub level

All the demo/examples I saw are filtering on the first level, but I want to do the array filtering with jq on the second level:

{
  "TheArray": [
    {
      "F1": "V11",
      "F2": "V12",
      "F3": "V13"
    },      
    {       
      "F1": "V21",
      "F2": "V22",
      "F3": "V33"
    }  ]
}

I want to filter with "F1" == "V11", and get:

{
  "TheArray": [
    {
      "F1": "V11",
      "F2": "V12",
      "F3": "V13"
    }  ]
}

Is that possible with jq?

Upvotes: 1

Views: 563

Answers (2)

oliv
oliv

Reputation: 13249

You can use this jq filter:

jq '.TheArray |= map(select(.F1=="V11"))' file

select command choose the right element and map is building the array based on the selected elements.

Upvotes: 2

peak
peak

Reputation: 116730

The following would be suitable if you want a solution that simply "edits" the original document, retaining any other keys that the top-level object might have:

.TheArray |= map(select(.F1=="V11"))

Variations

with_entries( .value |= map(select(.F1 == "V11")))

Another:

del(.TheArray[] | select(.F1!="V11"))

And if you have a more recent version of jq than version 1.5:

.TheArray[] |= select(.F1=="V11")

Upvotes: 1

Related Questions