<p>How to parse the json to retrieve a field from output of </p>

<pre><code>kubectl get pods -o json
</code></pre>

<p>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 :
<a href="https://i.stack.imgur.com/ysqWI.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ysqWI.png" alt="enter image description here"></a></p>

<p><a href="https://gist.github.com/scottstensland/278ce94dc6873aa54e44" rel="noreferrer">click here to see entire json output</a></p>

<p>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 </p>

<pre><code>.items[].metadata.name  
</code></pre>

<p>which so happens to have value :</p>

<pre><code>web-controller-5e6ij   // I need to retrieve this value
</code></pre>

<p><a href="https://kubernetes.io/docs/reference/kubectl/jsonpath/" rel="noreferrer">Here are docs on jsonpath</a></p>

<p>I want to avoid text parsing output of</p>

<pre><code>kubectl get pods
</code></pre>

<p>which is</p>

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

<p>Following will correctly parse this <code>get pods</code> command yet I feel its too fragile </p>

<pre><code>kubectl get pods | tail -1 | cut -d' ' -f1
</code></pre>

Scott Stensland
<p>After much battling this one liner does retrieve the container name :</p>

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

<p>when this is the known search criteria :</p>

<pre><code>items[].metadata.labels.name  == "web"
</code></pre>

<p>and this is the desired field to retrieve </p>

<pre><code>items[].metadata.name  :  "web-controller-5e6ij"
</code></pre>
