Skip to content

Instantly share code, notes, and snippets.

@pasenor
Last active December 8, 2015 09:24
Show Gist options
  • Save pasenor/5768f00491228c481576 to your computer and use it in GitHub Desktop.
Save pasenor/5768f00491228c481576 to your computer and use it in GitHub Desktop.
validate a json schema considering all fields required regardless of what's in the 'required' list
from jsonschema import Draft4Validator
from jsonschema.exceptions import ValidationError
myschema = {
'type': 'object',
'properties': {
'required_property': {
'type': 'string',
},
'optional_property': {
'type': 'string',
}
},
'required': ['required_property'],
'additionalProperties': False
}
first_instance = {
'required_property': 'somestring',
'optional_property': 'someotherstring'
}
second_instance = {
'required_property': 'somestring',
}
class AllRequiredValidator(Draft4Validator):
def __init__(self, schema):
super(AllRequiredValidator, self).__init__(schema)
self.VALIDATORS['required'] = self.required
@staticmethod
def required(validator, required, instance, schema):
if not validator.is_type(instance, 'object'):
return
all_properties = schema.get('properties', {})
for property in all_properties:
if property not in instance:
raise ValidationError("Evaluating in ALL_REQUIRED mode: '{}' must be present".format(property))
validator = AllRequiredValidator(myschema)
print 'validation of full instance: ', validator.validate(first_instance, myschema)
print 'validation of missing field: ', validator.validate(second_instance, myschema)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment