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.

46 lines
1.5 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. if "maxLength" in schema and len(obj) > schema["maxLength"]:
  12. raise ValidationError("%s is too long" % obj_name)
  13. elif schema.get("type") == "number":
  14. if not isinstance(obj, int):
  15. raise ValidationError("%s is not a number" % obj_name)
  16. if "minimum" in schema and obj < schema["minimum"]:
  17. raise ValidationError("%s is too small" % obj_name)
  18. if "maximum" in schema and obj > schema["maximum"]:
  19. raise ValidationError("%s is too large" % obj_name)
  20. elif schema.get("type") == "array":
  21. if not isinstance(obj, list):
  22. raise ValidationError("%s is not an array" % obj_name)
  23. for v in obj:
  24. validate(v, schema["items"], "an item in '%s'" % obj_name)
  25. elif schema.get("type") == "object":
  26. if not isinstance(obj, dict):
  27. raise ValidationError("%s is not an object" % obj_name)
  28. for key, spec in schema["properties"].items():
  29. if key in obj:
  30. validate(obj[key], spec, obj_name=key)
  31. if "enum" in schema:
  32. if obj not in schema["enum"]:
  33. raise ValidationError("%s has unexpected value" % obj_name)