You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

44 lines
1.4 KiB

  1. """ A minimal jsonschema validator.
  2. Supports only a tiny subset of jsonschema.
  3. """
  4. from six import string_types
  5. class ValidationError(Exception):
  6. pass
  7. def validate(obj, schema, obj_name="value"):
  8. if schema.get("type") == "string":
  9. if not isinstance(obj, string_types):
  10. raise ValidationError("%s is not a string" % obj_name)
  11. elif schema.get("type") == "number":
  12. if not isinstance(obj, int):
  13. raise ValidationError("%s is not a number" % obj_name)
  14. if "minimum" in schema and obj < schema["minimum"]:
  15. raise ValidationError("%s is too small" % obj_name)
  16. if "maximum" in schema and obj > schema["maximum"]:
  17. raise ValidationError("%s is too large" % obj_name)
  18. elif schema.get("type") == "array":
  19. if not isinstance(obj, list):
  20. raise ValidationError("%s is not an array" % obj_name)
  21. for v in obj:
  22. validate(v, schema["items"], "an item in '%s'" % obj_name)
  23. elif schema.get("type") == "object":
  24. if not isinstance(obj, dict):
  25. raise ValidationError("%s is not an object" % obj_name)
  26. for key, spec in schema["properties"].items():
  27. if key in obj:
  28. validate(obj[key], spec, obj_name=key)
  29. if "enum" in schema:
  30. if obj not in schema["enum"]:
  31. raise ValidationError("%s has unexpected value" % obj_name)