Tim Luka
Tim Luka

Reputation: 481

Get a specific value of JSON data

I'm getting a JSON data from RESTCONF HTTPS request, using the following code.

https_request = 'https://' + host + '/restconf/data/' + operation
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 data I got is:

{
    "Cisco-IOS-XE-native:Tunnel": {
        "name": 0,
        "bandwidth": {
            "kilobits": 256
        },
        "ip": {
            "address": {
                "primary": {
                    "address": "10.10.1.1",
                    "mask": "255.255.255.252"
                }
            }
        },
        "load-interval": 30,
        "Cisco-IOS-XE-tunnel:tunnel": {
            "source": "GigabitEthernet1",
            "destination": {
                "ipaddress-or-host": "10.2.1.3"
            }
        }
    }
}

Basically, I want my function to return the field's "bandwidth" value which is 256. I tried the following but it did not work.

capacity = r.json()['Cisco-IOS-XE-native:Tunnel']['bandwidth']

Upvotes: 1

Views: 420

Answers (1)

prosti
prosti

Reputation: 46479

Try this:

j={
    "Cisco-IOS-XE-native:Tunnel": {
        "name": 0,
        "bandwidth": {
            "kilobits": 256
        },
        "ip": {
            "address": {
                "primary": {
                    "address": "10.10.1.1",
                    "mask": "255.255.255.252"
                }
            }
        },
        "load-interval": 30,
        "Cisco-IOS-XE-tunnel:tunnel": {
            "source": "GigabitEthernet1",
            "destination": {
                "ipaddress-or-host": "10.2.1.3"
            }
        }
    }
}
print(j['Cisco-IOS-XE-native:Tunnel']['bandwidth'])

This returns:

{'kilobits': 256}

For 256:

print(j['Cisco-IOS-XE-native:Tunnel']['bandwidth']['kilobits'])

Upvotes: 1

Related Questions