jq – print value only where key value pair exists

I have json file like below. I want to print only the value of displayName when ‘"some_condition"’ doesnt exists or value is null. I cant seem to figure this out.

{
 "entities": [
    {
      "displayName": "host123.bcbsfl.com",
      "properties": {
        "kubernetesLabels": {
          "kubernetes.io/hostname": "host123.bcbsfl.com",
          "some_condition": "true",
          "kubernetes.io/arch": "amd64",
          "kubernetes.io/os": "linux",
          "beta.kubernetes.io/arch": "amd64",
          "node.openshift.io/os_id": "rhcos",
          "beta.kubernetes.io/os": "linux",
          "node-role.kubernetes.io/worker": ""
        }
      }
    },
    {
      "displayName": "host567.abc.com",
      "properties": {
        "kubernetesLabels": {
          "kubernetes.io/hostname": "host567.abc.com",
          "kubernetes.io/arch": "amd64",
          "kubernetes.io/os": "linux",
          "beta.kubernetes.io/arch": "amd64",
          "node.openshift.io/os_id": "rhcos",
          "beta.kubernetes.io/os": "linux",
          "node-role.kubernetes.io/worker": ""
        }
      }
    },
    ]
}

I have tried stuff like this but its not the output I’m looking for since it prints the whole object (sorry if terminology is off a bit. Im still trying to learn this).

jq -r ‘.entities[] |.displayName, select(.properties.kubernetesLabels.some_condition==null) ‘ file.json

>Solution :

You first have to select the objects you want, then feed the selected result into a new filter which extracts the display name:

.entities[]
| select(.properties.kubernetesLabels.some_condition==null)
| .displayName

Leave a Reply