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]
?()filter{.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 中的正則表示式

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