Kubernetes kubectl JSONPath Tester

Put the JSONPath template on the first line and paste the kubectl get ... -o json output under it. You get exactly the bytes kubectl would print, the values it matched, and a plain explanation of what the expression got wrong. This implements kubectl's own dialect rather than generic JSONPath, which is the only reason the answer is worth anything. Nothing is uploaded.

Paste below, or drop a file anywhere on this panel

Or drop a file anywhere on this panel. Nothing is uploaded: the analysis runs in this tab.

The answer appears here

Paste on the left and press Evaluate. Nothing leaves this tab.

Examples

Real input you can load into the tool above. Each one shows a different thing going wrong, because that is what the tool is for.

A range expression

kubectl's JSONPath dialect, which is not the same as the JSONPath everyone else uses

{range .items[*]}{.metadata.name}{"\n"}{end}
{"apiVersion":"v1","kind":"List","items":[{"metadata":{"name":"a"}},{"metadata":{"name":"b"}}]}

A filter

Selecting by a field value, and why the quoting differs between shells

{.items[?(@.status.phase=="Running")].metadata.name}
{"items":[{"metadata":{"name":"a"},"status":{"phase":"Running"}},{"metadata":{"name":"b"},"status":{"phase":"Pending"}}]}

Common mistakes

These are the ones that fail silently. The config is accepted, nothing raises an error, and the consequence arrives later.

  1. Assuming kubectl JSONPath is standard JSONPath

    kubectl implements its own dialect: range/end, no filters in some versions, and different quoting. Expressions from other tools often fail.

    Instead:Test against kubectl's dialect, which is what this page uses.

  2. Quoting wrongly for the shell

    Single quotes work in bash and not in PowerShell, and the expression itself contains braces the shell may expand.

    Instead:Wrap in single quotes on bash and double on PowerShell, escaping inner quotes.

  3. Expecting JSON output

    JSONPath output is text. Nested structures print in a Go format that is not JSON.

    Instead:Use -o json with jq when you need JSON out.

Where kubectl's JSONPath differs from everyone else's

Every one of these is a case where a generic JSONPath tester gives you a different answer from the cluster. The expression is read as k8s.io/client-go/util/jsonpath reads it: the same terminator set, the same bracket-key rule, the same filter grammar, the same strict subscript bounds, and the same printer.

['app.kubernetes.io/name'] is four path segments, not one key

This is the difference that catches everyone, and it is the opposite of every other JSONPath library. The bracket form is not a quoted literal: kubectl re-parses the contents as a path, so that expression asks for .app then .kubernetes then .io/name and matches nothing at all. Only ['app\.kubernetes\.io/name'] with a backslash before each dot asks for the key you meant. Since almost every label and annotation key in a real cluster contains dots, this is the single most common reason a jsonpath comes back empty.

A misspelled field prints nothing and exits 0

kubectl get runs with --allow-missing-template-keys=true, so a key that does not exist is not an error. You get a blank line, exit status 0, and no hint anywhere that the field was never found, which is indistinguishable from a field that exists and happens to be empty. This page names the exact step where the result set went empty and lists the keys that were actually present at that point, which is the part the command line will not tell you.

A range with no literal in it concatenates, it does not separate

Each brace group is printed as its own batch and absolutely nothing is written between batches. So {range .items[*]}{.metadata.name}{end} over three pods prints apiwebdb as one unbroken string. A plain {.items[*].metadata.name} prints them space separated instead, because those three values are inside a single batch and kubectl joins a batch with spaces. Two different mechanisms, and knowing which one you are in is the difference between a usable line and a mangled one.

The output is not JSON, and an object prints as map[...]

Every matched value goes through Go's fmt, so a path that stops at a mapping prints map[cpu:4 memory:8Gi] with the keys sorted, a list prints [a b c], and a JSON null prints the literal string <nil>. There is no quoting anywhere, so a value containing a space or a colon cannot be distinguished from structure. If the output has to be parsed rather than read, -o jsonpath-as-json is the flag, and it exists precisely because -o jsonpath does not give you JSON.

An index past the end is a hard error, a missing key is silent

These are two versions of the same typo with opposite outcomes. {.items[0].metadata.namez} prints nothing and exits 0. {.items[9].metadata.name} on a three-item list fails with "array index out of bounds: index 9, length 3" and exits non-zero. A slice is checked the same way, so [0:3] over two items also fails rather than returning what it can, which is not how a Python slice behaves and is not what anyone expects.

A filter is one comparison, and there are six operators

?(@.status.phase=="Running") is the shape. There is no &&, no ||, no grouping and no regular expression: the parser stops at the ampersand with an unrecognized character error, and =~ is read as a bare = which then fails at evaluation time with "unrecognized filter operator". A single = instead of == parses cleanly and fails the same way. The comparison is also typed: a whole JSON number arrives as an int64 and comparing it to a quoted string is refused outright rather than evaluating to false.

A wildcard over a mapping has no stable order

{.items[*]} keeps the order of the list, because a list is a slice. {.metadata.labels.*} does not, because a mapping is a Go map and Go randomises map iteration on purpose. The same command against the same unchanged object prints the same values in a different order on the next run. Recursive descent with .. has the same property wherever it crosses a mapping. Any script that reads the output positionally is broken and will look fine until it is not.

A field step on a list matches nothing, silently

{.items.metadata.name} does not map over the list. A field step looks inside a mapping only, so applied to a list it produces nothing at all, with no error. Most JSONPath libraries do implicitly descend into arrays there, which is why a path copied from a generic tester or a blog post prints an empty line here and reads as a broken cluster rather than a missing [*].

What a green verdict does not say: this evaluates the expression against the document you pasted, and a real cluster will hand kubectl a different one. A path that works on a two-pod list can still trip the out-of-bounds error on a busier namespace, and a filter that matches one object today matches none tomorrow. The values are also read as JSON types, so an integer here is an integer in kubectl too, but a fractional number written as 1.0 is a float in kubectl and an integer here, and a filter comparing the two kinds is refused. For anything the template cannot express, and that includes every condition needing two clauses, -o json piped into jq is the right tool and this page will say so rather than pretend.

What kubectl's JSONPath actually is

It is k8s.io/client-go/util/jsonpath: a small Go implementation with its own parser, its own filter grammar and its own printer. It shares a name and a rough shape with the JSONPath most libraries implement, and it disagrees with them on the details that decide whether your expression works. That is why a generic JSONPath tester will confirm an expression that kubectl then refuses, and why this page exists.

The braces are the whole model

A template is a sequence of brace groups with literal text between them. Anything outside a group is copied to stdout byte for byte with no processing at all, which is how formatted output gets built and also why an expression with no braces anywhere is echoed back at you rather than evaluated. Inside a group, a quoted string is a literal too, and that is the only place an escape such as \n means a newline.

{.metadata.name}          one group, one path

kind is {.kind}           text, group
                          prints: kind is List

.metadata.name            no braces at all
                          prints: .metadata.name

{.metadata.name}\n         the \n is outside the group,
                          so it prints a backslash
                          and the letter n

{.metadata.name}{"\n"}     the newline you wanted

range and end, and where the separators come from

range and end are two ordinary brace groups, not a block the parser balances for you. Between range and its end, everything is evaluated once per item. The part worth internalising: each group prints as its own batch, values within a batch are joined with one space, and nothing at all goes between batches. So every separator in a range has to be written by hand, and forgetting them produces one long run of concatenated values rather than an error.

{range .items[*]}{.metadata.name}{end}
  api-7d9fweb-5f6cdb-0

{.items[*].metadata.name}
  api-7d9f web-5f6c db-0
  (one batch, so kubectl joins with spaces)

{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}
  api-7d9f   Running
  web-5f6c   Pending
  db-0       Running

Escaping a dot, which you will need on nearly every label

A dot ends a field name. So does [ ] $ @ { } ( ) and whitespace. A slash and a comma do not, which is why the slash in an annotation key needs nothing and the dots need a backslash each. Both forms work and both need the escape, because the bracket form is re-parsed as a path rather than taken as a literal key. Backslashes are stripped from the name afterwards, all of them, so there is no way to have a literal backslash in a key.

wrong, matches nothing:
  {.metadata.annotations.kubernetes.io/change-cause}
  {.metadata.labels['app.kubernetes.io/name']}

right, both of these:
  {.metadata.annotations.kubernetes\.io/change-cause}
  {.metadata.labels['app\.kubernetes\.io/name']}

also note: a bracket key takes single quotes only.
["tier"] is rejected as an invalid array index,
which is a parse error before any input is read.

and a key with a dot in it turns up in ConfigMaps too:
  {.data.ca\.crt}

Filters, exactly

The grammar is one path, one operator, one value. The operator is any run of the characters ! < > = that the parser finds, which is why a wrong one gets all the way to evaluation before failing. The right-hand side can be a quoted string, a number, true or false, or another path starting from the current item. Omit the operator entirely and the filter keeps every item where the path exists at all, which is the idiomatic way to ask whether a field is set.

{.items[?(@.status.phase=="Running")].metadata.name}
{.items[?(@.spec.nodeName)].metadata.name}      exists
{.items[?(@.spec.replicas>2)].metadata.name}

operators, and there are only these six:
  ==  !=  <  <=  >  >=

not supported, at all:
  ?(@.a=="x" && @.b=="y")     parse error at the &
  ?(@.name=~/^web-/)          no regular expressions
  ?(@.a=="x") || ?(@.b=="y")  no OR anywhere
  ?(@.length-1)               no script expressions

types are checked, not coerced:
  ?(@.spec.replicas==3)    fine, both integers
  ?(@.status.phase==0)     "incompatible types
                            for comparison"

Subscripts, slices and the union

A subscript is an index, a slice, or a wildcard. A negative index counts back from the end and does not wrap. A step must be positive. The bounds are checked strictly and an out-of-range index or end is an error rather than a shorter result, which is the one place this dialect is louder than you would expect. A union takes a comma-separated list of paths and concatenates their results, in the order the branches are written.

{.items[0]}        first
{.items[-1]}       last
{.items[0:2]}      first two
{.items[0:6:2]}    every second, and only if
                   the list has at least 6 items
{.items[*]}        all
{.items[?(...)]}   filtered

{.items[*]['metadata.name', 'status.capacity']}
  127.0.0.1 127.0.0.2 map[cpu:4] map[cpu:8]

out of bounds is an error, not an empty result:
  {.items[9]}   on 3 items ->
  array index out of bounds: index 9, length 3

Recursive descent, and what it costs

Two dots descend to every level and collect every value that has children, then the next step filters those. It is the quickest way to find a field whose path you have forgotten. It is also a poor thing to put in a script: it crosses mappings, so the order of what comes back is not stable, and it will happily match a field of the same name at a depth you were not thinking about.

{..name}
  127.0.0.1 127.0.0.2 myself e2e

  four different objects, at three different
  depths, in an order that is stable for the
  list parts and random for the mapping parts

{..metadata.name}   still crosses everything;
                    narrow it with .items[*]
                    once you know the shape

What comes out, and the two flags that change it

Every matched value is printed with Go's fmt, which is what the reference page means by "the result object is printed as its String() function". A scalar prints as itself with no quoting. A mapping prints as map[k:v k:v] with the keys sorted, and a list as [a b c]. A key that exists holding JSON null prints <nil>, while a key that does not exist prints nothing, so those two situations look completely different in the output and identical on the command line.

-o jsonpath-as-json
  prints the matched values as a real JSON
  array, which is what you want whenever the
  output is going into another program

--allow-missing-template-keys=false
  turns a missing key back into an error and a
  non-zero exit. kubectl get defaults it to
  true, which is the reason a typo is silent.

  worth setting in a script even though nobody
  does, because the alternative is a variable
  that is quietly empty

Quoting it at a shell, which is a real source of failures

A template containing a space has to be quoted, and the quoting is not the same everywhere. bash and zsh want single quotes around the whole template so the double quotes around a newline literal survive. cmd.exe and PowerShell do not strip single quotes, so the same command hands kubectl a template with literal quote characters in it and the parse fails on something that works for everyone else on the team.

bash, zsh:
  kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}'

PowerShell, cmd:
  kubectl get pods -o jsonpath="{range .items[*]}{.metadata.name}{'\n'}{end}"

  single and double quotes swap round, and
  {'\n'} is just as valid as {"\n"} inside
  the braces

More kubernetes tools

Kubernetes YAML Generator Answer a few questions, get a manifest Kubernetes YAML Validator Is this YAML valid, and where is it wrong? Kubernetes Rollout & Probe Timing Restart loops, capacity dips and stuck drains Kubernetes Service Checker Will this Service have any endpoints? Kubernetes Network Policy Viewer What can reach what, and what just broke Kubernetes Manifest Diff What actually changed Kubernetes Resource Calculator What these manifests actually reserve Kubernetes RBAC Viewer Who can actually do what Kubernetes Deployment Generator See the capacity dip before you deploy Kubernetes Service Generator port, targetPort, and which one you meant Kubernetes StatefulSet Generator Stable names, and volumes that outlive you Kubernetes QoS Class Calculator And where you sit in the eviction order Kubernetes Node Capacity Planner Allocatable is not capacity Kubernetes Max Pods per Node Calculator The ENI limit, not the 110 default Kubernetes Label Selector Tester Which key failed, not just that one did Kubernetes Taint & Toleration Tester Tolerations permit, they do not attract Kubernetes Resource Name Validator RFC 1123 subdomain, label, or 1035 Kubernetes Label & Annotation Validator Why your image tag is not a legal label Kubernetes CrashLoopBackOff Guide The status is a timer, not a cause Kubernetes TLS Certificate Decoder When it expires, and what it covers Kubernetes ServiceAccount Token Decoder Bound or legacy, and when it dies Kubernetes imagePullSecret Generator The registry URL nobody gets right Kubernetes cert-manager Certificates Issuer scope, and the rate limit that costs a week Kubernetes Flux HelmRelease Generator With the source it cannot work without Kubernetes Helm Chart Generator Chart.yaml, values, and working templates Kubernetes Argo CD Application Generator The defaults that are off, turned on Kubernetes Ingress Generator pathType, and the TLS secret that fails quietly Kubernetes HPA Generator Why it says unknown and never scales Kubernetes SecurityContext Generator Pod level, container level, and which wins Kubernetes Probe Generator How long it gets to start before liveness kills it Kubernetes PVC Generator Access modes your storage can actually do Kubernetes ResourceQuota Generator And the LimitRange that stops it breaking deploys Kubernetes CronJob Generator The fields that decide whether it runs Kubernetes NetworkPolicy Generator With the DNS rule already in it Kubernetes RBAC Generator And what it actually grants Kubernetes PodDisruptionBudget Generator Can this budget ever be satisfied? Kubernetes API Deprecation Checker What breaks on the next upgrade Kubernetes Kubeconfig Viewer Read it without handing it to anyone Kubernetes Quantity Parser What 512Mi, 100m and 1e3 actually mean Kubernetes Multi-Document YAML Splitter One file per object, in apply order Kubernetes .env to ConfigMap & Secret Split the credentials out on the way Kubernetes Secret Decoder See what is actually in there Kubernetes Ingress to Gateway API Which annotations silently stop working Kubernetes Manifest Visualizer What points at what, and what points at nothing Kubernetes Patch Tester Which --type, and what it deletes Kubernetes Node Affinity Tester Required excludes, preferred only scores Kubernetes Helm Values Diff A missing key is a third value Kubernetes Pod and Service CIDR Fixed at cluster creation Kubernetes Secret Encoder base64 is not encryption Kubernetes API Version Checker Will this apply on that cluster Kubernetes Go Template Tester Go truthiness is not JavaScript's Kubernetes Cluster Cost Estimator At your rates, not a price table Kubernetes Kustomize Build Transformers run in kustomize's order Kubernetes Helm Chart Validator version is SemVer, appVersion is not

Elsewhere on the site