Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Check it online.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading