Bootstrap FreeKB - OpenShift - Parse JSON using jsonpath
OpenShift - Parse JSON using jsonpath

Updated:   |  OpenShift articles

If you are not familiar with the oc command, refer to OpenShift - Getting Started with the oc command.

Let's say you've a pod named hello-openshift. The oc get pod command with the --output json​ option can be used to display the pods JSON.

{
    "apiVersion": "v1",
    "kind": "Pod",
    "spec": {
        "containers": [
            {
                "image": "openshift/hello-openshift"
            }
        ]
    },
    "status": {
        "hostIP": "10.84.188.68",

 

jsonpath can be used to print the value of a specific JSON key.

~]$ oc get pod hello-openshift --output jsonpath={.apiVersion}
v1

 

And here is how to print the value of a non-array nested key.

~]$ oc get pod hello-openshift --output jsonpath={.status.hostIP}
10.84.188.68

 

Notice that the "containers" key is an array, as indicated by the bracket [ ] characters. One option is to include the index number of the array (0 in this example).

~]$ oc get pod hello-openshift --output jsonpath={.spec.containers[0].image}
openshift/hello-openshift

 

Or, you can use the wildcard * character to loop through the array, returning the value of each occurrence of a certain key in the array.

~]$ oc get clusterrolebinding openshift-admins-cluster-admin --output jsonpath={.subjects[*].name}
Openshift_Admin openshift_admins

 

And here is how you can return two (or more) values.

~]$ oc get pod hello-openshift --output jsonpath="{.apiVersion} {.status.hostIP}"
v1 10.84.188.68

 

Let's say you have a secret named my-cert that contains a key that contains a period (tls.crt in this example).

~]$ oc get secret my-cert --output json
{
    "apiVersion": "v1",
    "data": {
        "tls.crt": "LS0tLS1CRUdJTiBDRVJUS...",
        "kind": "Secret",
        "name": "my-cert"
    }
    "type": "kuberneters.io/tls"
}

 

To return the JSON of the tls.crt key, you'll need to place double quotes around jsonpath and escape the period in tls.crt.

~]$ oc get secret my-cert --output jsonpath="{.data.tls\.crt}"
LS0tLS1CRUdJTiB...

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 951a5b in the box below so that we can be sure you are a human.