Reputation: 481
I'm getting a JSON data from RESTCONF HTTPS request, using the following code.
https_request = 'https://' + host + '/restconf/data/Cisco-IOS-XE-native:native/interface/'
headers = {'Content-type': 'application/yang-data+json', 'Accept': 'application/yang-data+json'}
r = requests.get(https_request, auth=(user, password), headers=headers, verify=False)
print r.json()
The JSON file I got:
{
"Cisco-IOS-XE-native:interface": {
"GigabitEthernet": [
{
"name": "1",
"description": "DON'T TOUCH ME",
"isis": {
"Cisco-IOS-XE-isis:metric": {
"value": 2
}
....
},
{
"name": "2",
"isis": {
"Cisco-IOS-XE-isis:metric": {
"value": 4
} ....
},
{
"name": "3",
"shutdown": [
null
],
"isis": {
"Cisco-IOS-XE-isis:metric": {
"value": 7
}....
}
],
"Loopback": [
{
"name": 0,
"isis": {
"Cisco-IOS-XE-isis:metric": {
"value": 1
}
],
"Tunnel": [
{
"name": 0,
"isis": {
"Cisco-IOS-XE-isis:metric": {
"value": 3
}....
}
]
}
Basically, I want my function to return the field's "value"
of isis
of each interface. I tried the following code for GigabitEthernet
:
value = r.json()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][0]['isis']['metric']['value']
I got this error:
print Router_1.get_isis_metric()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][0]['isis']['metric']['isis']
KeyError: 'metric'
Upvotes: 0
Views: 454
Reputation: 20500
Using a list comprehension, where you iterate over the list of dictionaries and collect the value for each interface, example for GigabitEthernet
dct = {
"Cisco-IOS-XE-native:interface": {
"GigabitEthernet": [
{
"name": "1",
"description": "DON'T TOUCH ME",
"isis": {
"Cisco-IOS-XE-isis:metric": {
"value": 2
}}
},
{
"name": "2",
"isis": {
"Cisco-IOS-XE-isis:metric": {
"value": 4
}}
},
{
"name": "3",
"shutdown": [
None
],
"isis": {
"Cisco-IOS-XE-isis:metric": {
"value": 7
}}
}
]}}
result = [item['isis']["Cisco-IOS-XE-isis:metric"]['value'] for item in dct['Cisco-IOS-XE-native:interface']['GigabitEthernet']]
The output will be
[2, 4, 7]
Or to collect values for all interfaces, you can loop over the interfaces and collect the value for each interface
interfaces = ['GigabitEthernet', 'Loopback', 'Tunnel']
result = [item['isis']["Cisco-IOS-XE-isis:metric"]['value'] for interface in interfaces for item in dct['Cisco-IOS-XE-native:interface'][interface]]
print(result)
The output will be
[2, 4, 7, 1, 3]
Upvotes: 3
Reputation: 7268
I think, you have misspelled metric
for Cisco-IOS-XE-isis:metric
Try :
value = r.json()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][0]['isis']['Cisco-IOS-XE-isis:metric']['value']
Edit 1
for index in range(len(r.json()['Cisco-IOS-XE-native:interface']['GigabitEthernet'])):
value = r.json()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][index]['isis']['Cisco-IOS-XE-isis:metric']['value']
print(value)
Upvotes: 5