我有來自 Juniper 交換機的這個 JSON 輸出,我需要在其中獲取與 lldp_local_parent_interface_name
具有 value關聯的遠程系統名稱ae0
。
因此,我只知道該值ae0
,并且我需要獲取遠程系統名稱A_B_C_D
才能開始以該主機為目標來執行一些其他任務。
檔案juniper-data.json中的資料如下所示:
{
"output": {
"lldp_neighbors_information": [{
"lldp_neighbor_information": [{
"lldp_local_parent_interface_name": [{
"data": "ae0"
}],
"lldp_local_port_id": [{
"data": "xe_0/2/0"
}],
"lldp_remote_chassis_id": [{
"data": "00:00:00:00:00:00:00"
}],
"lldp_remote_chassis_id_subtype": [{
"data": "Mac address"
}],
"lldp_remote_port_description": [{
"data": "xe_1/0/1"
}],
"lldp_remote_system_name": [{
"data": "A_B_C_D"
}]
},
{
"lldp_local_parent_interface_name": [{
"data": "_"
}],
"lldp_local_port_id": [{
"data": "ge_0/0/23"
}],
"lldp_remote_chassis_id": [{
"data": "xx:xx:xx:xx:xx:xx"
}],
"lldp_remote_chassis_id_subtype": [{
"data": "Mac address"
}],
"lldp_remote_port_description": [{
"data": "bond0"
}]
}
]
}]
}
}
以下是我的任務:
- name: load data to var
set_fact:
remote_sys_name: "{{ lookup('file', 'juniper-data.json') | from_json }}"
- name: view loaded data
debug:
var: item
loop: "{{ remote_sys_name | community.general.json_query('output.lldp_neighbors_information[0].lldp_neighbor_information[*].[?lldp_local_parent_interface_name[0].data=='ae0'].lldp_remote_system_name[0].data') }}"
預期成績
"item": "A_B_C_D"
我得到的是
致命的:[本地主機]:失敗!=> {“msg”:“模板錯誤,同時模板字串:預期令牌',',得到'ae0'。字串:{{ remote_sys_name | community.general.json_query('output.lldp_neighbors_information[0].lldp_neighbor_information[*]. [?lldp_local_parent_interface_name[0].data=='ae0'].lldp_remote_system_name[0].data') }}"}
uj5u.com熱心網友回復:
如果您不關心節點的確切層次結構及其旁邊的名稱lldp_neighbor_information
,則可以使用一組物件投影和展平投影來簡化它:
*.*[][].*[][?
lldp_local_parent_interface_name[0].data == 'ae0'
][].lldp_remote_system_name[].data
至于您當前的嘗試,問題在于您的條件錯誤地位于該位:
lldp_neighbor_information[*].[?lldp_local_parent_interface_name[0].data=='ae0']
條件應該實際替換明星:
lldp_neighbor_information[?lldp_local_parent_interface_name[0].data=='ae0']
以查詢結束:
output
.lldp_neighbors_information[0]
.lldp_neighbor_information[?
lldp_local_parent_interface_name[0].data=='ae0'
]
.lldp_remote_system_name[0]
.data
鑒于任務:
- debug:
var: item
loop: >-
{{
lookup('file', 'juniper-data.json')
| from_json
| json_query('
output
.lldp_neighbors_information[0]
.lldp_neighbor_information[?
lldp_local_parent_interface_name[0].data==`ae0`
]
.lldp_remote_system_name[0]
.data
')
}}
這產生:
ok: [localhost] => (item=A_B_C_D) =>
ansible_loop_var: item
item: A_B_C_D
獎勵:如果事先知道您將只有一個元素,您也可以結束查詢| [0]
以停止投影并僅獲取第一個元素。
這樣,您可以擺脫回圈:
- debug:
var: remote_sys_name
vars:
remote_sys_name: >-
{{
lookup('file', 'juniper-data.json')
| from_json
| json_query('
output
.lldp_neighbors_information[0]
.lldp_neighbor_information[?
lldp_local_parent_interface_name[0].data==`ae0`
]
.lldp_remote_system_name[0]
.data | [0]
')
}}
立即產生名稱:
ok: [localhost] =>
remote_sys_name: A_B_C_D
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/497238.html
上一篇:反序列化字串時出現JsonConvert.DeserializeObject錯誤
下一篇:如何映射嵌套的D3物件并創建陣列