我對 jq 有一個復雜的(至少對我來說)問題,這個結構:
{
"os": {
"ubuntu": {
"16.04": {
"codename": "xenial",
"bootstrap": "preseed",
"guest_type": "ubuntu64Guest",
"iso_name": "ubuntu-16.04.7-server-amd64.iso",
"iso_checksum": "9bb30a2ea6466b0c02aacfa96f6e3516",
},
"18.04": {
"codename": "bionic",
"bootstrap": "preseed",
"guest_type": "ubuntu64Guest",
"iso_name": "ubuntu-18.04.2-server-amd64.iso",
"iso_checksum": "34416ff83179728d54583bf3f18d42d2",
"arm": {
"iso_name": "ubuntu-18.04.5-server-arm64.iso",
"iso_checksum": "5056eaf87425b550376e6733b05de6e9"
}
}
},
"rhel": {
"7.4": {
"codename": "maipo",
"bootstrap": "kickstart",
"guest_type": "rhel7_64Guest",
"iso_name": "rhel-server-7.4-x86_64-boot.iso",
"iso_checksum": "94ad0929b79b5d13b33acafc8da8d364",
},
"7.6": {
"codename": "maipo",
"bootstrap": "kickstart",
"guest_type": "rhel7_64Guest",
"iso_name": "rhel-server-7.6-x86_64-boot.iso",
"iso_checksum": "4a611d2bbfa6912eada91096af14ec84",
}
}
}
}
我需要通過使用“18.04”搜索來獲取“ubuntu”節點內容,而不知道“ubuntu”節點鍵名。因此,如果我搜索名為“7.4”的子節點,它應該將其父節點標識為“rhel”并回傳它。
基本上,使用作業系統版本,我應該得到作業系統名稱,但我無法事先知道作業系統名稱。
我嘗試了一些命令(沒有讓他們感到抱歉),在這個備忘單的幫助下,沒有運氣: https ://gist.github.com/olih/f7437fb6962fb3ee9fe95bda8d2c8fa4
甚至有可能嗎?
謝謝。
uj5u.com熱心網友回復:
我需要獲取“ubuntu”節點內容
您可以.[]用來獲取所有節點的內容,并has檢查它們的密鑰:
jq '.os[] | select(has("18.04"))'
{
"16.04": {
"codename": "xenial",
"bootstrap": "preseed",
"guest_type": "ubuntu64Guest",
"iso_name": "ubuntu-16.04.7-server-amd64.iso",
"iso_checksum": "9bb30a2ea6466b0c02aacfa96f6e3516"
},
"18.04": {
"codename": "bionic",
"bootstrap": "preseed",
"guest_type": "ubuntu64Guest",
"iso_name": "ubuntu-18.04.2-server-amd64.iso",
"iso_checksum": "34416ff83179728d54583bf3f18d42d2",
"arm": {
"iso_name": "ubuntu-18.04.5-server-arm64.iso",
"iso_checksum": "5056eaf87425b550376e6733b05de6e9"
}
}
}
演示
如果您想要包含“ubuntu”欄位的物件,請更新|=節點:
jq '.os | .[] |= select(has("18.04"))'
{
"ubuntu": {
"16.04": {
"codename": "xenial",
"bootstrap": "preseed",
"guest_type": "ubuntu64Guest",
"iso_name": "ubuntu-16.04.7-server-amd64.iso",
"iso_checksum": "9bb30a2ea6466b0c02aacfa96f6e3516"
},
"18.04": {
"codename": "bionic",
"bootstrap": "preseed",
"guest_type": "ubuntu64Guest",
"iso_name": "ubuntu-18.04.2-server-amd64.iso",
"iso_checksum": "34416ff83179728d54583bf3f18d42d2",
"arm": {
"iso_name": "ubuntu-18.04.5-server-arm64.iso",
"iso_checksum": "5056eaf87425b550376e6733b05de6e9"
}
}
}
}
演示
uj5u.com熱心網友回復:
基本上,使用作業系統版本,我應該得到作業系統名稱,但我無法事先知道作業系統名稱。
您可以使用to_entires()withselect()和has()過濾那些嵌套物件包含所需鍵的物件:select(.value | has("18.04")).
然后回傳父密鑰以獲取作業系統名稱 ( .key):
.os | to_entries[] | select(.value | has("18.04")).key
// "ubuntu"
.os | to_entries[] | select(.value | has("7.6")).key
// "rhel"
JqPlay 演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/515329.html
