JSONPath Output
JSONPath is a query language for extracting specific fields from kubectl's JSON output. It is more concise than piping through jq and works directly with the -o jsonpath flag.
Basic Syntax
# Get the name of a specific pod
kubectl get pod my-app -o jsonpath='{.metadata.name}'
# Get the pod's IP address
kubectl get pod my-app -o jsonpath='{.status.podIP}'
# Get the container image
kubectl get pod my-app -o jsonpath='{.spec.containers[0].image}'
JSONPath expressions are wrapped in curly braces. Fields are accessed with dot notation, and array elements use bracket indexing.
Extracting from Lists
The wildcard [*] iterates over all items in a list:
# Get all pod names in the current namespace
kubectl get pods -o jsonpath='{.items[*].metadata.name}'
# Output: pod-a pod-b pod-c
Using range for Formatted Output
The range function lets you loop and format output line by line:
# Print each pod name on its own line
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}'
# Print name and status on each line
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'
Filtering with Conditions
Use the ?() syntax to filter based on conditions:
# Get names of pods in Running phase
kubectl get pods -o jsonpath='{.items[?(@.status.phase=="Running")].metadata.name}'
# Get container names that have restart count > 0
kubectl get pods -o jsonpath='{.items[*].status.containerStatuses[?(@.restartCount>0)].name}'
Practical Examples
# Get all node IP addresses
kubectl get nodes -o jsonpath='{.items[*].status.addresses[?(@.type=="InternalIP")].address}'
# Get the cluster IP of a service
kubectl get svc my-service -o jsonpath='{.spec.clusterIP}'
# Get all images running in the cluster
kubectl get pods -A -o jsonpath='{.items[*].spec.containers[*].image}' | tr ' ' '\n' | sort -u
Key Takeaways
- JSONPath expressions go inside
'{...}'with the-o jsonpathflag - Use
[*]for wildcards andrange/endfor iteration - Filter with
?(@.field=="value")for conditional extraction - Combine with
trorsortfor post-processing