我正在使用以下代码从RESTCONF HTTPS请求中获取JSON数据。
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()
我得到的JSON文件:
{
"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
}....
}
]
}
基本上,我希望函数返回每个接口的"value"
的字段isis
。我为GigabitEthernet
尝试了以下代码:
value = r.json()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][0]['isis']['metric']['value']
我收到此错误:
print Router_1.get_isis_metric()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][0]['isis']['metric']['isis']
KeyError: 'metric'
答案 0 :(得分:5)
我认为您为metric
拼错了Cisco-IOS-XE-isis:metric
尝试:
value = r.json()['Cisco-IOS-XE-native:interface']['GigabitEthernet'][0]['isis']['Cisco-IOS-XE-isis:metric']['value']
编辑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)
答案 1 :(得分:3)
使用列表推导,在其中迭代字典列表并收集每个接口的值,例如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']]
输出将为
[2, 4, 7]
或者要收集所有接口的值,可以遍历接口并收集每个接口的值
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)
输出将为
[2, 4, 7, 1, 3]