Using jq, remove keys that match a regular expression

Viewed 850

I'd like to remove any fields that match a regular expression, while preserving all other fields and the structure of the JSON. For example, suppose the JSON looks like this.

{
  "this": {
    "foobar": {
      "that": "too"
    },
    "baz": 3,
    "foo": 1
    "morefoo": {
      "foosball": "hi"
    }
  }
}

Then the desired output would be

{
  "this": {
    "baz": 3,
    "morefoo": {}
  }
}

It's possible to do this cleanly by explicitly naming the fields as discussed here:

Delete objects and arrays with jq which match a key

jq 'del(.. | .foo?, .foobar?, .foosball?)'

but I would like to do this with a regular expression, something like

jq 'del(.. | .("^foo")?)'  # This does not work

Suggestions? If possible, I'd rather avoid with_entries, but if that's the only way, then so be it.

1 Answers

Here's a simple solution using walk:

walk(if type=="object"
     then with_entries(select(.key | test("^foo") | not))
     else . end)
Related