How to parse json format output of : kubectl get pods using jsonpath
In addition to Scott Stensland answer, a way to format your results:
kubectl get pods -o=jsonpath='{range .items[?(@.metadata.labels.name=="web")]}{.metadata.name}{"/n"}'
This add newlines. You can also do {", "} to output comma with space.
Another solution:
Use JQ to get a nicely formatted json result:
kubectl get pods -o json | jq -r '.items[] | [filter] | [formatted result]' | jq -s '.'
Example of [filter]:
select(.metadata.labels.name=="web")
Example of [formatted result] (you can add more fields if your want):
{name: .metadata.name}
jq -s '.', for putting result objects in array.
To wrap it up:
kubectl get pods -o json | jq -r '.items[] | select(.metadata.labels.name=="web") | {name: .metadata.name}' | jq -s '.'
Then afterwards you can use this json data to get the desired output result.
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"
If you want to filter by labels. You could just use the kubectl -l
flag. The following will do the same:
kubectl get pods -l name=web -o=jsonpath='{.items..metadata.name}'