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

JSON filter a JSON with wildcards and keynames

How to parse a JSON to when a few values are string and other are list.

I have a list like this:

{
  "abc": {
    "enabled": true
  },
  "def": {
    "enabled": false
  },
  "ghi": [
    {
      "enabled": false,
      "name": "HELLO",
      "useless": "DO NOT WANT THIS"
    }
  ],
  "jkl": [
    {
      "enabled": true,
      "name": "HI"
    }
  ],
  "mko": {
    "enabled": false,
    "something unwanted": 123
  },
  "pqr": {
    "enabled": true
  }
}

Trying to filter only by the two key(enabled and name like abc):

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

{
  "abc": {
    "enabled": true
  },
  "def": {
    "enabled": false
  },
  "ghi": [
    {
      "enabled": false,
      "name": "HELLO"
    }
  ],
  "jkl": [
    {
      "enabled": true,
      "name": "HI"
    }
  ],
  "mko": {
    "enabled": false
  },
  "pqr": {
    "enabled": true
  }
}

Tried several answers on SO, but nothing is giving the desired result. I am not a regular consumer of JSON so this question might sounds stupid.

jq -r '[*].enabled' file
jq: error: syntax error, unexpected '*' (Unix shell quoting issues?) at <top-level>, line 1:
[*].enabled
jq: 1 compile error

>Solution :

You can use a combination of objects and arrays to select the items to update with |=, then with_entries to access the .key which can be queried with IN:

< file jq '
  (.[] | objects, (arrays[] | objects))
    |= with_entries(select(.key | IN("enabled", "name")))
'
{
  "abc": {
    "enabled": true
  },
  "def": {
    "enabled": false
  },
  "ghi": [
    {
      "enabled": false,
      "name": "HELLO"
    }
  ],
  "jkl": [
    {
      "enabled": true,
      "name": "HI"
    }
  ],
  "mko": {
    "enabled": false
  },
  "pqr": {
    "enabled": true
  }
}

Demo

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