Rob Kinyon
Rob Kinyon

Reputation: 1900

filtering a nested array with jq

I've got the following JSON:

{
  "x": [
    { "a": 1 },
    { "a": 2 },
    { "b": 1 },
    { "b": 2 }
  ]
}

I want to filter it so that I get back:

{
  "x": [
    { "b": 1 },
    { "b": 2 }
  ]
}

I've tried

".x[] | select(.b)"

But, that gives me back just a list of the objects with b as so:

{ "b": 1 }
{ "b": 2 }

I want the original surrounding object as well. (The full JSON is much larger and with much deeper nesting.)

Upvotes: 0

Views: 464

Answers (1)

peak
peak

Reputation: 117027

Unfortunately your general requirements are unclear, but hopefully the following solution to the class of problems suggested by the example will provide the guidance you seek:

.x |= map(select(has("b")))

Upvotes: 2

Related Questions