3

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"]

2 Answers 2

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

Check it online.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use to_entries function such as

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

Demo

2 Comments

jq version 1.5-1 produces an error: jq: error (at <stdin>:1): Invalid path expression near attempt to iterate through ["customer"]. In jq version 1.6 this works fine.
well, OK, as there were no mention about the version within the question I replied so ... @Jurc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.