How to parse json format output of : kubectl get pods using jsonpath

3/24/2016

How to parse the json to retrieve a field from output of

kubectl get pods -o json

From the command line I need to obtain the system generated container name from a google cloud cluster ... Here are the salient bits of json output from above command : enter image description here

click here to see entire json output

So the top most json key is an array : items[] followed by metadata.labels.name where the search critera value of that compound key is "web" (see above image green marks). On a match, I then need to retrieve field

.items[].metadata.name  

which so happens to have value :

web-controller-5e6ij   // I need to retrieve this value

Here are docs on jsonpath

I want to avoid text parsing output of

kubectl get pods

which is

NAME                     READY     STATUS    RESTARTS   AGE
mongo-controller-h714w   1/1       Running   0          12m
web-controller-5e6ij     1/1       Running   0          9m

Following will correctly parse this get pods command yet I feel its too fragile

kubectl get pods | tail -1 | cut -d' ' -f1
-- Scott Stensland
google-cloud-platform
json
kubernetes
parsing

2 Answers

3/24/2016

After much battling this one liner does retrieve the container name :

kubectl get pods -o=jsonpath='{.items[?(@.metadata.labels.name=="web")].metadata.name}'

when this is the known search criteria :

items[].metadata.labels.name  == "web"

and this is the desired field to retrieve

items[].metadata.name  :  "web-controller-5e6ij"
-- Scott Stensland
Source: StackOverflow

6/27/2018

If you want to filter by labels. You could just use kubectl -l flag. The following will do the same:

kubectl get pods -l name=web -o=jsonpath='{.items..metadata.name}'

-- Bunnyc1986
Source: StackOverflow