更新時間:2022-09-19 10:24:16 來源:動力節點 瀏覽1426次
如何通過jq獲取父元素值?動力節點小編來給大家舉例說明。
代碼:
{
"endpointAgents":[
{
"agentId": "MyId",
"agentName": "MYNAME",
"location": {
"locationName": "location"
},
"clients": [
{
"userProfile": {
"userName": "Name"
},
"browserExtensions": [
{
"active": false
}
]
},
],
"totalMemory": "16222 MB",
"agentType": "enterprise"
}
需要返回值為userName的agentId值。知道如何使用 JSONPath,但不知道jq如何。
($.endpointAgents[?(@.clients.userName=~ 'a')].agentId)
假設輸入 JSON 是
{
"endpointAgents": [
{
"agentId": "MyId",
"agentName": "MYNAME",
"location": {
"locationName": "location"
},
"clients": [
{
"userProfile": {
"userName": "Name"
},
"browserExtensions": [
{
"active": false
}
]
}
],
"totalMemory": "16222 MB",
"agentType": "enterprise"
}
]
}
要從數組的所有項中獲取agentId值,其中在同一個對象中,數組中至少有一個對象具有包含給定子字符串的字符串值,可以選擇endpointAgentsclientsuserProfile.userName
jq -r '
.endpointAgents[]
| select(.clients | map(.userProfile.userName | contains("a")) | any)
| .agentId
'
MyId
為了從 jq 外部導入查詢字符串,請使用--arg參數
jq -r --arg query "a" ' … contains($query) … '
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習