I have a python function that I want to check if a certain field is present in the json that is passed through. Essentially I want to throw an error if the field exists.
I have something that works
def check_groups(names):
json_names = json.loads(names)
for i in json_names:
try:
#check to make sure no groups have been passed through
if(i['groups']):
print('in if')
raise Exception()
except TypeError:
#this means there is no groups in the json so all is ok
print('ok')
except Exception:
raise Exception('Do not pass through groups')
As you can see, it isn't great logically and I obviously have to have a line of code after except TypeError (in this case print('ok')
which I don't really want/need to do.
Essentially, if the json has a field called groups
, I want to throw an error. If not, just continue.
The json is simple, here is an example of how it looks with the unwanted field provided:
[{"field_1": ["$.id"], "groups": "ABC"}]
I found the below code in some forums, I think this looks very simple,