Jsonpath With Objects
(this post is part of the material I cover in my devops course)
JSONPath is a query language for querying values in JSON strings.
It can help you navigate complex JSON values to retreive a specific value, or set of values.
JSON in kubernetes
- You can instruct kubernetes to modify the output to json:
1$> kubectl get pods
2NAME READY STATUS RESTARTS AGE
3my-pod 1/1 Running 0 12s
4$> kubectl get pods -o json
5{
6 "apiVersion": "v1",
7 "items": [
8 {
9 "apiVersion": "v1",
10 "kind": "Pod",
11 "metadata": {
12 "annotations": {
13 "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Pod\",\"metadata\":{\"annotations\":{},\"name\":\"my-pod\",\"namespace\":\"default\"},\"spec\":{\"containers\":[{\"command\":[\"sleep\",\"3600\"],\"image\":\"busybox:latest\",\"name\":\"busybox\"}]}}\n"
14 },
15 "creationTimestamp": "2024-05-12T12:51:10Z",
16 "name": "my-pod",
17. . . . . ..
18. . . . .
- As we can see, json definition can be complex.
It may be even worse if there are multiple object (we get an array of object):
1$> kubectl get pods
2NAME READY STATUS RESTARTS AGE
3busybox-deployment-1-79f4bf4474-k26p4 1/1 Running 0 50s
4busybox-deployment-1-79f4bf4474-w6f7h 1/1 Running 0 50s
5busybox-deployment-1-79f4bf4474-xjxsn 1/1 Running 0 50s
6$>
7$> kubectl get pods -o json
8{
9 "apiVersion": "v1",
10 "items": [
11 {
12 "apiVersion": "v1",
13 "kind": "Pod",
14 "metadata": {
Using JSONPATH with kubectl
- JSONPATH usage with kubectl is covered here
- Here's an example:
(I have a deployment with 3 pods for the examples here)
1$> kubectl get pods -o jsonpath='{$}'
(note that we get a single object with everything)
1kubectl get pods -o jsonpath='{$.items}'
(now the result starts with a square bracket, to specify the array)
1kubectl get pods -o jsonpath='{$.items[1]}'
2kubectl get pods -o jsonpath='{$.items[-1]}'
(getting just a single pod, then the last pod)
1kubectl get pods -o jsonpath='{$.items[0].spec.nodeName}'
2kubectl get pods -o jsonpath='{$.items[*].spec.nodeName}'
(just the nodeName of the first pod, then the names of all pods)