Home > database >  Kubectl json path select a field with special characters
Kubectl json path select a field with special characters

Time:09-02

I want to write a kubectl command to query all the namespace and then collect the value of a specific lable.

{
"apiVersion": "v1",
"items": [
    {
        "apiVersion": "v1",
        "kind": "Namespace",
        "metadata": {
            "annotations": {
                "kubectl.kubernetes.io/last-applied-configuration": "{\"apiVersion\":\"v1\",\"kind\":\"Namespace\",\"metadata\":{\"annotations\":{},\"labels\":{\"app.kubernetes.io/created-by\":\"testuser\",\"app.kubernetes.io/instance\":\"thisisatest\",\"app.kubernetes.io/name\":\"company\",\"app.kubernetes.io/version\":\"2.5\"},\"name\":\"thisiatest\"}}\n"
            },
            "creationTimestamp": "2022-09-01T13:16:12Z",
            "labels": {
                "app.kubernetes.io/created-by": "testuser",
                ...

I have a version with jq that works.

printf "\ncreated by:\n"
kubectl get namespace -l app.kubernetes.io/name=phoenics -o json | jq '.items [] | .metadata | .labels | ."app.kubernetes.io/created-by"'

But i can't really get a version with jsonpath to work. What am i doing wrong?

printf "\ncreated by: JsonPath\n"
kubectl get namespace -l app.kubernetes.io/name=phoenics -o jsonpath="{range ['items'][*]['metadata']['labels']['app.kubernetes.io/created-by']}{'\n'}{end}"

There is no output. Oh, and i'm working on windows with a git bash.

CodePudding user response:

this should work:

kubectl get namespace -l app.kubernetes.io/name=phoenics \
-o jsonpath="{range .items[*]}{.metadata.labels.app\.kubernetes\.io/created-by}{'\n'}{end}"

CodePudding user response:

Try:

kubectl get namespace -l app.kubernetes.io/name=phoenics -o jsonpath="{range ['items'][*]}{['metadata']['labels']['app.kubernetes.io/created-by']}{'\n'}{end}"
  • Related