Add new line when printing data using jsonpath

kubectl jsonpath output formatting new lines custom delimiters

2 min read | by Jordi Prats

When we print values using jsonpath we'll get all the values in a single line (actually, it won't even bother adding the newline character at the end of the list):

$ kubectl get ns -o jsonpath='{ .items[*].metadata.name }'
default dynamodb-operator ec2-operator iam-operator kube-node-lease kube-public kube-system local-path-storage testvault

To be able to add the new line character after each item we'll nee to iterate over it using range and append {"\n"} after each item:

$ kubectl get ns -o jsonpath='{ range .items[*]}{.metadata.name}{"\n"}{end}'
default
dynamodb-operator
ec2-operator
iam-operator
kube-node-lease
kube-public
kube-system
local-path-storage
testvault

It's not limited to new lines, so we can use it to make it output some custom format as well. In the following example we are printing the creation timestamp using a comma as delimiter:

$ kubectl get ns -o jsonpath='{ range .items[*]}{.metadata.name}{","}{.metadata.creationTimestamp}{"\n"}{end}'
default,2023-05-12T21:15:47Z
dynamodb-operator,2023-05-29T21:24:26Z
ec2-operator,2023-05-16T21:58:59Z
iam-operator,2023-06-01T19:49:21Z
kube-node-lease,2023-05-12T21:15:45Z
kube-public,2023-05-12T21:15:45Z
kube-system,2023-05-12T21:15:45Z
local-path-storage,2023-05-12T21:15:50Z
testvault,2023-05-12T21:17:07Z

Posted on 06/06/2023