Search code examples
pythonjsonschemapython-jsonschema

Validate datetime value using python jsonschema


I'm using jsonschema to validate my python dictionary. I' trying to validate a datetime value but I'm not sure how to do it.

Here's what I have so far, which results in an error because jsonschema doesn't have a datetime type:

order = {
    "name": "shirt",
    "order_datetime": datetime.datetime(2018, 1, 18)
}

schema = {
    "title": "Order",
    "type": "object",
    "required": ["name", "order_datetime"],
    "properties": {
        "name": {
            "type": "string"
        },
        "order_datetime": {
            "type": "datetime"
        }
    }
}

from jsonschema import validate
validate(order, schema)

The error is jsonschema.exceptions.SchemaError: 'datetime' is not valid under any of the given schemas. How can I validate this correctly?


Solution

  • Here's how to properly validate with a native Python datetime object. Assumes you have jsonschema 3.x:

    from datetime import datetime
    import jsonschema
    
    def validate_with_datetime(schema, instance):
      BaseVal = jsonschema.Draft7Validator
    
      # Build a new type checker
      def is_datetime(checker, inst):
        return isinstance(inst, datetime)
      date_check = BaseVal.TYPE_CHECKER.redefine('datetime', is_datetime)
    
      # Build a validator with the new type checker
      Validator = jsonschema.validators.extend(BaseVal, type_checker=date_check)
    
      # Run the new Validator
      Validator(schema=schema).validate(instance)