如何获取json对象的名称,以便在if语句中匹配它?
def test():
device_config = api_get_conf()
routing_protocol = device_config['Cisco-IOS-XE-native:native']
if 'ospf' in routing_protocol:
print('It worked!')
else:
print('dunno')routing_protocol变量中包含以下信息:
{"Cisco-IOS-XE-ospf:router-ospf": {
"ospf": {
"process-id": [
{
"id": 100,
"area": [
{
"area-id": 0,
"authentication": {
"message-digest": [
null
]
}
}
],
"network": [
{
"ip": "192.168.200.200",
"wildcard": "0.0.0.0",
"area": 0
}
]
}
]
}
}
}我只想匹配'Cisco-IOS-XE-ospf:router-ospf‘或'ospf’。任何关于我如何做到这一点的帮助将不胜感激。
发布于 2020-03-30 08:11:45
我不明白你的意思,但是看起来api_get_conf()返回字典,其中"Cisco-IOS-XE-ospf:router-ospf“是第一个键,它的值是另一个字典,其中键是"ospf”。如果这是您想要比较的,那么您可以简单地使用routing_protocol dict上的.keys()方法。
def test():
device_config = api_get_conf()
routing_protocol = device_config['Cisco-IOS-XE-native:native']
if 'ospf' in routing_protocol.keys():
print('It worked!')
else:
print('dunno')发布于 2020-03-30 08:03:37
def test():
device_config = api_get_conf()
# since we use get here, if we dont find it we set routing_protocol as False, easier to use on if
routing_protocol = device_config.get('Cisco-IOS-XE-native:native', False)
if routing_protocol:
if 'ospf' in routing_protocol:
print('It worked!')
print("ospf not a key")
else:
print('routing protocol not a key')https://stackoverflow.com/questions/60922248
复制相似问题