How to check json to ensure field is not present in python

Submitted 3 years, 6 months ago
Ticket #179
Views 257
Language/Framework Python
Priority Low
Status Closed

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"}]

Submitted on Sep 28, 20
add a comment

1 Answer

Verified

I found the below code in some forums, I think this looks very simple,

​
def check_groups(names):
    json_names = json.loads(names)
    for i in json_names:
        if 'groups' in i:
            raise AttributeError('Do not pass through groups')
        else:
            print('ok')

Submitted 3 years, 6 months ago


Latest Blogs