JSONPath 支持

  1. 在 JSONPath 表达式中使用双引号来引用文本。
  2. 使用 range, end 操作符来遍历列表。
  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"}
    }
  ]
}
函数、参数、示例调用以及结果
函数描述示例结果
文本纯文本kind 为 {.kind}kind 为 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
range, end遍历列表{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 中的正则表达式

# 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:JSONPath 示例 (709cdcd319)