How can I get the name of json object so that I can match on it in an if statement?
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')
The routing_protocol variable has the following information in it:
{"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
}
]
}
]
}
}
}
I would like to match on only 'Cisco-IOS-XE-ospf:router-ospf' or 'ospf'. Any help on how I can do this would be appreciated.
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')
I'm not sure what you mean, but it looks like api_get_conf() returns Dictionary where "Cisco-IOS-XE-ospf:router-ospf" is first key, and its value is another dictionary where key is "ospf". If it's what you wants to compare then you can simply use .keys() method on routing_protocol dict.
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')
Related
JSON OUTPUT:
${response}= [
{
"Name":"7122Project",
"checkBy":[
{
"keyId":"NA",
"target":"1232"
}
],
"Enabled":false,
"aceess":"123"
},
{
"Name":"7122Project",
"checkBy":[
{
"keyId":"_GU6S3",
"target":"123"
}
],
"aceess":"11222",
"Enabled":false
},
{
"Name":"7122Project",
"checkBy":[
{
"keyId":"-1lLUy",
"target":"e123"
}
],
"aceess":"123"
}
]
Need to get the keyId values from json without using hardcoded index using robot?
I did
${ID}= set variable ${response[0]['checkBy'][0]['keyId']}
But I need to check the length get all keyID values and store the values that dose not contain NA
How can I do check length and use for loop using robot framework?
I suppose you can have more elements in checkBy arrays, like so:
response = [
{
"Name":"7122Project",
"checkBy": [
{
"keyId": "NA",
"target": "1232"
}
],
"Enabled": False,
"aceess": "123"
},
{
"Name": "7122Project",
"checkBy": [
{
"keyId": "_GUO6g6S3",
"target": "123"
}
],
"aceess": "11222",
"Enabled": False
},
{
"Name": "7122Project",
"checkBy": [
{
"keyId": "-1lLlZOUy",
"target": "e123"
},
{
"keyId": "test",
"target": "e123"
}
],
"aceess": "123"
}
]
then you can key all keyIds in Python with this code:
def get_key_ids(response):
checkbys = [x["checkBy"] for x in response]
key_ids = []
for check_by in checkbys:
for key_id in check_by:
key_ids.append(key_id["keyId"])
return key_ids
for the example above, it will return: ['NA', '_GUO6g6S3', '-1lLlZOUy', 'test_NA'].
You want to get both ids with NA and without NA, so perhaps you can change the function a bit:
def get_key_ids(response, predicate):
checkbys = [x["checkBy"] for x in response]
key_ids = []
for check_by in checkbys:
for key_id in check_by:
if predicate(key_id["keyId"]):
key_ids.append(key_id["keyId"])
return key_ids
and use it like so:
get_key_ids(response, lambda id: id == "NA") # ['NA']
get_key_ids(response, lambda id: id != "NA") # ['_GUO6g6S3', '-1lLlZOUy', 'test_NA']
get_key_ids(response, lambda id: "NA" in id) # ['NA', 'test_NA']
get_key_ids(response, lambda id: "NA" not in id) # ['_GUO6g6S3', '-1lLlZOUy']
Now it's just a matter of creating a library and importing it into RF. You can get inspiration in the official documentation.
But I need to check the length get all keyID values and store the values that dose not contain NA
I don't completely understand what you are up to. Do you mean length of keyId strings, like "NA" and its length of 2, or the number of keyIds in the response?
How can I do check length and use for loop using robot framework?
You can use keyword Should Be Equal * from BuiltIn library. Some examples of for loops could be found in the user guide here.
Now you should have all the parts you need to accomplish your task, you can try to put it all together.
I have a scenario where I am trying to extract data from json response which is obtained from the GET request and then rebuilding the json data by changing some values and then sending a PUT request at same time after rebuilding the json data(i.e, after changing idter value)
below is the target json response.
target_json = {
"name": "toggapp",
"ts": [
1234,
3456
],
"gs": [
{
"id": 4491,
"con": "mno"
},
{
"id": 4494,
"con": "hkl"
}
],
"idter": 500,
"datapart": false
}
from the above json I am trying to change the idter value to my custom value and rebuild it into json data again and post the new json data.
Here is what I have tried :
headers = {'Authorization': 'bearer ' + auth_token, 'Content-Type':'application/json', 'Accept':'application/json'}
tesstid =[7865, 7536, 7789]
requiredbdy = []
for key in testid:
get_metadata_targetjson= requests.get('https://myapp.com/%s' %key, headers = headers)
metadata=get_metadata_target.json()
for key1 in metadata:
requiredbdy.append(
{
"metadata" : [{
"name": key1['name'],
"ts": key1['ts'],
"gs": key1[gs],
"idter": 100, #custom value which I want to change
"datapart": false
} ]
}
)
send_metadata_newjson= requests.put('https://myapp.com/%s' %key, headers = headers data = requiredbdy)
print(send_metadata_newjson.status_code)
Is this approach fine or How do I proceed in order to achieve this scenario.
You can use the built-in json module for this like so
import json
my_json = """
{
"name": "toggapp",
"ts": [
1234,
3456
],
"gs": [
{
"id": 4491,
"con": "mno"
},
{
"id": 4494,
"con": "hkl"
}
],
"idter": 500,
"datapart": false
}
"""
json_obj = json.loads(my_json)
json_obj['idter'] = 600
print(json.dumps(json_obj))
Prints
{"name": "toggapp", "ts": [1234, 3456], "gs": [{"id": 4491, "con": "mno"}, {"id": 4494, "con": "hkl"}], "idter": 600, "datapart": false}
There's this small script used it to find entries in some very long and unnerving JSONs. not very beautifull und badly documented but maybe helps in your scenario.
from RecursiveSearch import Retriever
def alter_data(json_data, key, original, newval):
'''
Alter *all* values of said keys
'''
retr = Retriever(json_data)
for item_no, item in enumerate(retr.__track__(key)): # i.e. all 'value'
# Pick parent objects with a last element False in the __track__() result,
# indicating that `key` is either a dict key or a set element
if not item[-1]:
parent = retr.get_parent(key, item_no)
try:
if parent[key] == original:
parent[key] = newval
except TypeError:
# It's a set, this is not the key you're looking for
pass
if __name__ == '__main__':
alter_data(notification, key='value',
original = '********** THIS SHOULD BE UPDATED **********',
newval = '*UPDATED*')
I'm trying to create an Ansible module to use Batfish inside an Ansible playbook.
I'm comparing JSON values with defined variables in function. But it can compare only one JSON value and variable in the function. How do I use loop and return?
I have already tried extract values from each JSON and tried to compare with defined variable.
import json
json_list = {"batfish_result": [
{
"Action": {
"0": "DENY"
},
"Line_Content": {
"0": "no-match"
}
},
{
"Action": {
"0": "PERMIT"
},
"Line_Content": {
"0": "permit 10.20.0.0 255.255.255.0"
}
}
]
}
def main(json_list):
PASS = 'PASS'
FAIL = 'FAIL'
result = {}
result_list = []
action_num_list = []
condition_list = ['permit', 'permit']
jsons = json_list["batfish_result"]
for j in jsons:
print(j)
action = j['Action']
action_num = action["0"]
action_num_list.append(action_num)
for con in condition_list:
for action in action_num_list:
if action == con.upper():
result_list.append(PASS)
result['msg'] = result_list
else:
result_list.append(FAIL)
result['msg'] = result_list
return result
main(json_list)
It returns
{'msg': ['PASS', 'PASS']}
It should be comparing each action with each condition variable like this.
{ "msg": ['FAIL', 'PASS'] }
Finally I solved it like this;
import json
from pprint import pprint
json_list = {"batfish_result": [
{
"Action": {
"0": "DENY"
},
"Line_Content": {
"0": "no-match"
}
},
{
"Action": {
"0": "PERMIT"
},
"Line_Content": {
"0": "permit 10.20.0.0 255.255.255.0"
}
}
]
}
def main(json_list):
PASS = "PASS"
FAIL = "FAIL"
result = {}
result_list = []
action_num_list = []
condition_list = ["permit", "permit"]
jsons = json_list["batfish_result"]
for j in jsons:
action = j['Action']
action_num = action["0"]
action_num_list.append(action_num)
#[DENY, PERMIT]
for con in condition_list:
con = con
#for action in action_num_list:
for x, y in zip(condition_list, action_num_list):
if y == x.upper():
result_list.append(PASS)
result['msg'] = result_list
#if pprint(y) != pprint(x.upper()):
else:
result_list.append(FAIL)
result['msg'] = result_list
return result_list
main(json_list)
Because pprint always returns 'None'. So I had to remove pprint after debug and also I used loop too much.
With this code
import sense
import json
sense.api_key = '...'
node = sense.Node.retrieve('........')
feed = node.feeds.retrieve('presence')
events = feed.events.list(limit=1)
result = json.dumps(events,indent=1)
print result
I get a JSON-Feed like this:
{
"links": {...},
"objects": [
{
"profile": "GenStandard",
"feedUid": ".....",
"gatewayNodeUid": ".....",
"dateServer": "2015-02-28T09:57:22.337034",
"geometry": null,
"data": {
"body": "Present",
"code": 200
},
"signal": "-62",
"dateEvent": "2015-02-28T09:57:22.000000",
"type": "presence",
"payload": "2",
"nodeUid": "....."
}
],
"totalObjects": 875,
"object": "list"
}
How can I check if 'body' is 'present' (or 'code' is '200')? My script should return TRUE or FALSE
UPDATE
If I add this code as proposed in the answers it works fine:
d=json.loads(result)
def checkJson(jsonContents):
bodyFlag = True if "body" in jsonContents["objects"][0]["data"] and jsonContents["objects"][0]["data"]["body"] == "Present" else False
return bodyFlag
print checkJson(d)
You should also maybe check if the body key is actually there.
def checkJson(jsonContents):
bodyFlag = True if "body" in jsonContents["objects"][0]["data"] and jsonContents["objects"][0]["data"]["body"] == "Present" else False
codeFlag = True if "code" in jsonContents["objects"][0]["data"] and jsonContents["objects"][0]["data"]["code"] == 200 else False
return bodyFlag or codeFlag
print checkJson(result)
d = json.loads(results)
objs = d["objects"][0]
# see if any code is either == 200 or "body" is a key in the subdict
return any(x for x in (objs["data"]["code"] == 200,"body" in objs["data"]))
I have JSON that looks like this:
{
"ROLE_NAME": {
"FOO": {
"download_url": "http: //something.staging/12345/buzz.zip"
},
"BAR": {
"download_url": "http: //something.staging/12345/fizz.zip"
},
"download_url": "http: //something.staging/12345/fizzbuzz.zip",
"db_name": "somedb",
"db_server": "dbserver.staging.dmz",
"plugin": {
"server_url": "http: //lab.staging.corp/server/"
}
}
}
I wrote a bit of python that replaces the "download_url" k:v with a new value (i.e. new download_url). Unfortunately it only replaces one of the three download_urls in that json snippet. I understand why, but am having a little difficulty getting the solution, and so I am here asking for help.
The entire json object is "data"
So I do something like this:
data["ROLE_NAME"]["download_url"] = download_url
Where download_url is a new value I have assigned to that variable
What I need to do is for any key called ["download_url"] then update it, rather than the one I have specified at the layer I am going to.
Some of my code to help:
I take some values obtained earlier in my code and build a url which returns a response. I extract a value from the response which will be used to build the value of download_url
buildinfo_url = "http://something.staging/guestAuth/app/rest/builds/?locator=buildType:%s,tags:%s,branch:branched:any" % (
bt_number,
list_json_load[role_name][0]['tag']
)
Send HTTP request
client = httplib2.Http()
response, xml = client.request(buildinfo_url)
Extract some value from the response xml and set download_url variable
doc = ElementTree.fromstring(xml)
for id in doc.findall('build'):
build_id = "%s" % (id.attrib['id'])
try:
download_url = "http://something.staging/guestAuth/repository/download/%s/%s:id/%s" % (
bt_number,
build_id,
build_artifact_zip
)
data[role_name]["download_url"] = download_url
except NameError:
print "something"
I think I should be recursively searching and updating
Using recursion
import json
json_txt = """
{
"ROLE_NAME": {
"FOO": {
"download_url": "http: //something.staging/12345/buzz.zip"
},
"BAR": {
"download_url": "http: //something.staging/12345/fizz.zip"
},
"download_url": "http: //something.staging/12345/fizzbuzz.zip",
"db_name": "somedb",
"db_server": "dbserver.staging.dmz",
"plugin": {
"server_url": "http: //lab.staging.corp/server/"
}
}
}
"""
data = json.loads(json_txt)
def fixup(adict, k, v):
for key in adict.keys():
if key == k:
adict[key] = v
elif type(adict[key]) is dict:
fixup(adict[key], k, v)
import pprint
pprint.pprint( data )
fixup(data, 'download_url', 'XXX')
pprint.pprint( data )
Output:
{u'ROLE_NAME': {u'BAR': {u'download_url': u'http: //something.staging/12345/fizz.zip'},
u'FOO': {u'download_url': u'http: //something.staging/12345/buzz.zip'},
u'db_name': u'somedb',
u'db_server': u'dbserver.staging.dmz',
u'download_url': u'http: //something.staging/12345/fizzbuzz.zip',
u'plugin': {u'server_url': u'http: //lab.staging.corp/server/'}}}
{u'ROLE_NAME': {u'BAR': {u'download_url': 'XXX'},
u'FOO': {u'download_url': 'XXX'},
u'db_name': u'somedb',
u'db_server': u'dbserver.staging.dmz',
u'download_url': 'XXX',
u'plugin': {u'server_url': u'http: //lab.staging.corp/server/'}}}