Filter out sub-array items that contain a specific key/value pair

Viewed 308

I want to use jq to filter out sub-array items that contain a specific key/value pair without filtering out the non-array data.

Input:

{
  "log": {
    "foo": {
      ...
    },
    "entries": [
      {
        "request": {
          "method": "OPTIONS",
          "url": "http://www.foobar.com"
        }
      },
      {
        "request": {
          "method": "GET",
          "url": "http://www.foobar.com"
        }
      }
    ]
  }
}

Desired output:

{
  "log": {
    "foo": {
      ...
    },
    "entries": [
      {
        "request": {
          "method": "GET",
          "url": "http://www.foobar.com"
        }
      }
    ]
  }
}

I have tried this:

jq '(.log.entries[] | select(.request.method != "OPTIONS"))'

But then I lose the all of the JSON data above entries.

2 Answers

Use |= assignment operator for modifying sub-elements in-place, e.g:

.log.entries |= map(select(.request.method != "OPTIONS"))

Directly use the del() operation on the object that matches your condition

del(.log.entries[] | select(.request.method == "OPTIONS"))
Related