JSONPath 支援
Kubectl 支援 JSONPath 範本。
JSONPath 範本由大括號 {} 括住的 JSONPath 運算式組成。Kubectl 使用 JSONPath 運算式來篩選 JSON 物件中的特定欄位並格式化輸出。除了原始的 JSONPath 範本語法外,以下函數和語法也有效
- 使用雙引號來引用 JSONPath 運算式內的文字。
- 使用
range
、end
運算子來迭代清單。 - 使用負切片索引在清單中向後逐步執行。負索引不會「環繞」清單,並且只要
-index + listLength >= 0
就有效。
注意
$
運算子是選用的,因為運算式預設一律從根物件開始。結果物件會以其 String() 函數列印。
假設 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} | 種類為 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 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}'
注意
在 Windows 上,您必須雙引號任何包含空格的 JSONPath 範本 (而不是如上方 bash 所示的單引號)。這反過來表示您必須在範本中的任何常值周圍使用單引號或跳脫雙引號。例如
kubectl get pods -o=jsonpath="{range .items[*]}{.metadata.name}{'\t'}{.status.startTime}{'\n'}{end}"
kubectl get pods -o=jsonpath="{range .items[*]}{.metadata.name}{\"\t\"}{.status.startTime}{\"\n\"}{end}"
注意
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'
上次修改時間:2023 年 7 月 28 日 太平洋標準時間上午 10:47:修正 JSONPath 支援頁面中不一致的指令 (2987c60d92)