JSONPath 支持

kubectl 工具支持 JSONPath 模板作为输出格式。

JSONPath 模板 由花括号 {} 括起来的 JSONPath 表达式组成。 Kubectl 使用 JSONPath 表达式来筛选 JSON 对象中的特定字段并格式化输出。 除了原始 JSONPath 模板语法之外,以下函数和语法也有效

  1. 在 JSONPath 表达式中使用双引号来引用文本。
  2. 使用 rangeend 操作符来迭代列表。
  3. 使用负切片索引向后遍历列表。
    负索引不会“循环”列表,只要 \( ( - index + listLength ) \ge 0 \) 成立,它们就是有效的。

Kubernetes JSONPath 中的函数

给定 JSON 输入

{
  "kind": "List",
  "items":[
    {
      "kind":"None",
      "metadata":{
        "name":"127.0.0.1",
        "labels":{
          "kubernetes.io/hostname":"127.0.0.1"
        }
      },
      "status":{
        "capacity":{"cpu":"4"},
        "addresses":[{"type": "LegacyHostIP", "address":"127.0.0.1"}]
      }
    },
    {
      "kind":"None",
      "metadata":{"name":"127.0.0.2"},
      "status":{
        "capacity":{"cpu":"8"},
        "addresses":[
          {"type": "LegacyHostIP", "address":"127.0.0.2"},
          {"type": "another", "address":"127.0.0.3"}
        ]
      }
    }
  ],
  "users":[
    {
      "name": "myself",
      "user": {}
    },
    {
      "name": "e2e",
      "user": {"username": "admin", "password": "secret"}
    }
  ]
}
函数、其参数、示例调用和结果
功能描述示例结果
text纯文本kind is {.kind}kind is List
@当前对象{@}与输入相同
.[]子运算符{.kind}{['kind']}{['name\.type']}List
..递归下降{..name}127.0.0.1 127.0.0.2 myself e2e
*通配符。获取所有对象{.items[*].metadata.name}[127.0.0.1 127.0.0.2]
[start:end:step]下标运算符{.users[0].name}myself
[,]联合运算符{.items[*]['metadata.name', 'status.capacity']}127.0.0.1 127.0.0.2 map[cpu:4] map[cpu:8]
?()过滤器{.users[?(@.name=="e2e")].user.password}secret
rangeend迭代列表{range .items[*]}[{.metadata.name}, {.status.capacity}] {end}[127.0.0.1, map[cpu:4]] [127.0.0.2, map[cpu:8]]
''引用解释的字符串{range .items[*]}{.metadata.name}{'\t'}{end}127.0.0.1 127.0.0.2
\转义终止字符{.items[0].metadata.labels.kubernetes\.io/hostname}127.0.0.1

在 kubectl 中使用 JSONPath 表达式

使用 kubectl 和 JSONPath 表达式的示例

kubectl get pods -o json
kubectl get pods -o=jsonpath='{@}'
kubectl get pods -o=jsonpath='{.items[0]}'
kubectl get pods -o=jsonpath='{.items[0].metadata.name}'
kubectl get pods -o=jsonpath="{.items[*]['metadata.name', 'status.capacity']}"
kubectl get pods -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.startTime}{"\n"}{end}'
kubectl get pods -o=jsonpath='{.items[0].metadata.labels.kubernetes\.io/hostname}'

或者,使用“my_pod”和“my_namespace”(根据您的环境调整这些名称)

kubectl get pod/my_pod -n my_namespace -o=jsonpath='{@}'
kubectl get pod/my_pod -n my_namespace -o=jsonpath='{.metadata.name}'
kubectl get pod/my_pod -n my_namespace -o=jsonpath='{.status}'

JSONPath 中的正则表达式

不支持 JSONPath 正则表达式。 如果您想使用正则表达式进行匹配,可以使用 jq 等工具。

# kubectl does not support regular expressions for JSONpath output
# The following command does not work
kubectl get pods -o jsonpath='{.items[?(@.metadata.name=~/^test$/)].metadata.name}'

# The following command achieves the desired result
kubectl get pods -o json | jq -r '.items[] | select(.metadata.name | test("test-")).metadata.name'
最后修改时间:2025 年 4 月 6 日 7:02 AM PST:JSONPath 示例 (709cdcd319)