2

I'm new to the world of Python. My question is what is the best way (if any way is already done without doing it by hand) to perform validations of object attributes in Python.

The task is that when I receive data coming to me in a JSON from the client (for example an HTTP request to create an article), I want to check that this data is good (It is not a string when it should be an int (age), etc).

I have an object, and the object has the field age, i don't want to do this always. I want somethig that do it for me.

if age >= 18: 
    print("You are able to vote in the United States!")
else:
    print("You are not able to vote in the United States.")

I've looked for several things but I can't find a good module or library to perform this important validation task. If anyone knows one with good documentation or shows an example, it would be appreciated.

RodriKing
  • 822
  • 2
  • 10
  • 20
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – dot.Py May 08 '18 at 13:39
  • Instead of using an 'input' you can use your `JSON` data – dot.Py May 08 '18 at 13:40
  • @dot.Py, The dup might not be the best applicable.. You don't need a `while True` loop to keep on asking for json. The rest, of course, is sound advice. – jpp May 08 '18 at 13:41
  • 1
    @RodriKing, Can you give **specific** validation(s) you wish to perform with example data? Otherwise, I fear this question is too broad. – jpp May 08 '18 at 13:43
  • @jpp I want validate fields of an object. – RodriKing May 08 '18 at 13:49

2 Answers2

0

Python has built-in JSON module to work with JSON data, read more here. As well you can try the jsonschema validator module.

Christian
  • 76
  • 3
0

Make your own validator func. This is just an example how it works.

data = {'age': 18, 'hair': 'brown'}      # Create dict variable
def validator(value):                    # Create a function that receives argument
    if isinstance(value, int):           # Check the type of passed argument
        print('It is a number.')         # Prints if it is a number
    else:
        raise ValueError('It is a %s'%type(value))  # If not number Error is raised

validator(data['age'])  #  Test 1
validator(data['hair'])  # Test 2
Goran
  • 259
  • 1
  • 9