Jurc
Jurc

Reputation: 23

jq: Delete objects from an array based on its key

I want to use jq to delete all objects from an array whose key does not correspond to a defined value.

This is my JSON:

{
  "name": "config1",
  "children": [
    {
      "customer": {
        "name": "cust1"
      }
    },
    {
      "filter": {
        "name": "test1"
      }
    },
    {
      "filter": {
        "name": "test2"
      }
    },
    {
      "context": {
        "id": "1"
      }
    }
  ]
}

For example I want to remove all objects whose key is not "filter". Desired output:

{
  "name": "config1",
  "children": [
    {
      "filter": {
        "name": "test1"
      }
    },
    {
      "filter": {
        "name": "test2"
      }
    }
  ]
}

I tried

jq 'del(.children[] | with_entries(select(.key != "filter")))'

but that gives the following error:

jq: error (at <stdin>:1): Invalid path expression near attempt to iterate through ["customer"]

Upvotes: 2

Views: 3571

Answers (2)

axiac
axiac

Reputation: 72266

jq 'del(.children[] | select(.filter == null))'

Check it online.

Upvotes: 2

Barbaros &#214;zhan
Barbaros &#214;zhan

Reputation: 65363

You can use to_entries function such as

jq 'del(.children[] | select( to_entries[] | .key != "filter"))'

Demo

Upvotes: 2

Related Questions