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

Problem with JQ selecting specific keys based on selecting

I have a problem with JQ where I can’t get the correct fields. I have don’t so many tutorials but can’t seem to get this. I am trying to get only the "cpu" for the "mysql" container, but I keep getting both "sidecar, and mysql". Honestly I think it is my misunderstanding of JQ so please feel free to point out what I am misunderstanding.

I keep getting the following but should ONLY see "2100m":

null
2100m

jq -r –arg _NAME "mysql-innodb-cluster-0" #Only get the container with this specific name

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

‘.items[] #Work on all items

| select(.metadata.name == $_NAME ) #Work on the container that has this name

| .spec.containers #Get the specific key, which will be an object here.

select(.[].name=="sidecar" | not ) #Now that you have the Container Array only use the one that IS NOT named "sidecar"

| .[].resources.limits.cpu ‘ #you now have the MySQL container get ONLY it’s "cpu" value.

Command I use:

jq -r --arg _NAME "mysql-innodb-cluster-0" '.items[] | select(.metadata.name == $_NAME ) | .spec.containers | select(.[].name=="sidecar" | not ) | .[].resources.limits.cpu ' --raw-output /tmp/test.json

test.json

{
 "apiVersion": "v1",
"items": [
{
  "apiVersion": "v1",
  "kind": "Pod",
  "metadata": {
    "name": "mysql-innodb-cluster-0"
  },
  "spec": {
    "containers": [
      {
        "name": "sidecar",
        "resources": {}
      },
      {
        "name": "mysql",
        "resources": {
          "limits": {
            "cpu": "2100m",
            "memory": "5G"
          }
        }
      }
    ]
  }
}
 ],
"kind": "List"
}

>Solution :

After you selected the correct name, you’ll need to continue select‘ing on the .spec.containers to find the one with name === "mysql" and then select the .resources.limits.cpu from that object:

.items[] | select(.metadata.name == $_NAME) | (.spec.containers[] | select(.name == "mysql").resources?.limits?.cpu)

Will output:

"2100m"

Online JqPlay 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