this is the raw data I want to search this using json_query in ansible with keyvalue=65060 and print the corresponding Neighbor, can anyone please help.
so far I got this:
- name: data manipulate
debug: msg="{{ msnjson | json_query(msnquery) }}"
vars:
msnquery: "[*].AS"
but this just displays all AS keys but I'm looking for exactly the key with value 65060 and corresponding Neighbor Key.
[
{
"AS": "65060",
"InQ": "0",
"MsgRcvd": "258259",
"MsgSent": "120410",
"Neighbor": "99.99.99.5",
"OutQ": "0",
"Spk": "0",
"StPfxRcd": "1",
"TblVer": "2241",
"UpDown": "2w0d"
},
{
"AS": "64600",
"InQ": "0",
"MsgRcvd": "281828",
"MsgSent": "120498",
"Neighbor": "192.168.100.1",
"OutQ": "0",
"Spk": "0",
"StPfxRcd": "33",
"TblVer": "2241",
"UpDown": "12w5d"
},
{
"AS": "64600",
"InQ": "0",
"MsgRcvd": "281867",
"MsgSent": "120498",
"Neighbor": "192.168.100.2",
"OutQ": "0",
"Spk": "0",
"StPfxRcd": "33",
"TblVer": "2241",
"UpDown": "12w5d"
},
{
"AS": "64600",
"InQ": "0",
"MsgRcvd": "258516",
"MsgSent": "120499",
"Neighbor": "192.168.100.4",
"OutQ": "0",
"Spk": "0",
"StPfxRcd": "19",
"TblVer": "2241",
"UpDown": "5w6d"
}
]
Try
- name: data manipulate
debug: msg="{{ msnjson | json_query(msnquery) }}"
vars:
msnquery: "[?AS=='65060'].Neighbor"
Update
There are multiple items with the same value of AS. It might be practical to create a dictionary if you have to search Neighbor by AS repeatedly. For example,
AS_Neighbors: "{{ [msnjson|json_query(msnquery), []]|
community.general.lists_mergeby('AS', list_merge='append')|
items2dict(key_name='AS', value_name='Neighbor') }}"
msnquery: "[].{AS: AS, Neighbor: [Neighbor]}"
gives
AS_Neighbors:
'64600':
- 192.168.100.1
- 192.168.100.2
- 192.168.100.4
'65060':
- 99.99.99.5
Example of a complete playbook for testing
- hosts: localhost
vars:
AS_Neighbors: "{{ [msnjson|json_query(msnquery), []]|
community.general.lists_mergeby('AS', list_merge='append')|
items2dict(key_name='AS', value_name='Neighbor') }}"
msnquery: "[].{AS: AS, Neighbor: [Neighbor]}"
msnjson:
- AS: '65060'
InQ: '0'
MsgRcvd: '258259'
MsgSent: '120410'
Neighbor: 99.99.99.5
OutQ: '0'
Spk: '0'
StPfxRcd: '1'
TblVer: '2241'
UpDown: 2w0d
- AS: '64600'
InQ: '0'
MsgRcvd: '281828'
MsgSent: '120498'
Neighbor: 192.168.100.1
OutQ: '0'
Spk: '0'
StPfxRcd: '33'
TblVer: '2241'
UpDown: 12w5d
- AS: '64600'
InQ: '0'
MsgRcvd: '281867'
MsgSent: '120498'
Neighbor: 192.168.100.2
OutQ: '0'
Spk: '0'
StPfxRcd: '33'
TblVer: '2241'
UpDown: 12w5d
- AS: '64600'
InQ: '0'
MsgRcvd: '258516'
MsgSent: '120499'
Neighbor: 192.168.100.4
OutQ: '0'
Spk: '0'
StPfxRcd: '19'
TblVer: '2241'
UpDown: 5w6d
tasks:
- debug:
var: AS_Neighbors