Search code examples
pythonjsonapi

Validate specific value in JsonSchema with Python


Friends, given structure below how to validate if the "title" field must contain the value "delectus aut autem"

I would also like to know if the gender field has the "male/female" value as I would validate too.

def test_get():
 response = requests.get(ENDPOINT)
 assert response.status_code == 200
 data = response.json()
 print(data)
 print(data['title'])

def test_body():
 schema = {
   "type": "object",
    "properties": {
        "id": {"type": "integer"},
        "title": {"type": "string"},
        
    },
}

 validate(instance={"id": 1, "title": "delectus aut autem"}, schema=schema)
# No error, the JSON is valid.

Solution

  • Try this and see if this suits your requirements:
    (you can modify the snippet as per your logic, this is just example to get the idea)

    Also for more information on how to validate fields you can refer below doc.
    JSON Schema Validation

    import json
    import jsonschema
    from jsonschema import validate
    
    
    # Describe what kind of json you expect.
    studentSchema = {
      "type": "object",
      "properties": {
        "id": {
          "type": "integer"
        },
        "title": {
          "enum": ["delectus", "aut", "autem"] 
          # put this entire string if you want to be specifc -> "delectus aut autem"
          # "enum": ["delectus aut autem"]
        },
        "gender": {
          "enum": ["male", "female"]
        }
      }
    }
    
    
    def validateJson(jsonData):
        try:
            validate(instance=jsonData, schema=studentSchema)
        except jsonschema.exceptions.ValidationError as err:
            return False
        return True
    
    
    # Convert json to python object.
    jsonData = json.loads('{"title": "delectus", "id": 1, "gender": "male"}')
    
    # validate it
    isValid = validateJson(jsonData)
    if isValid:
        print(jsonData)
        print("Given JSON data is Valid")
    else:
        print(jsonData)
        print("Given JSON data is InValid")