6
votes

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?

3
The docs suggest that it's spelled with a dash 'date-time'. And looking at one of the schemas it's described as "a valid date-time string", not a datetime instance.Steven Rumbalski
@StevenRumbalski I need to validate a datetime instanceJohnny Metz
Follow the first link on my comment to @sobek's answer which shows how to extend types. Instead of extending number you would extend date-time.Steven Rumbalski
If you are not actually planning to dump to JSON and just want to validate your dictionary use schema.Steven Rumbalski

3 Answers

12
votes

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)
2
votes

Once you add rfc3339-validator or strict-rfc3339 to project dependencies (the first one is much more accurate as I can see), jsonschema.FormatChecker class will register the date-time format validator. So the code will be as simple, as it should be:

from jsonschema import (
    Draft7Validator,
    FormatChecker,
)

schema = {
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "datetime": {
      "type": "string",
      "format": "date-time"
    }
  }
}

validator = Draft7Validator(schema, format_checker=FormatChecker())
data_samples = [
    {'datetime': '2021-01-01T00:01:02.003+01:00'},
    {'datetime': '2021-01-01'},
]
assert validator.is_valid(data_samples[0]) is True
assert validator.is_valid(data_samples[1]) is False

You can have a look at other possible to use formats, libraries they require, and other tips at jsonschema documentation page.

1
votes

With help of @speedplane's answer, I was able to get the type checker working for my case of order_datetime.

order = {
    "name": "shirt",
    "order_datetime": "2019-09-13-22.30.00.000000"
}

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

Python code

import jsonschema
def validate_with_datetime(schema, instance):
  BaseVal = jsonschema.Draft7Validator
  # Build a new type checker
  def is_datetime(checker, inst):
     try:
        datetime.datetime.strptime(inst, '%Y-%m-%d-%H.%M.%S.%f')
        return True
     except ValueError:
        return False
  date_check = BaseVal.TYPE_CHECKER.redefine(u'orderdatetime', 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)

validate_with_datetime(schema, order)

But while exploring jsonschema library, I came across FormatChecker(). Can't we use jsonschema.FormatChecker() to validate the format of datetime type property ?

@speedplane Can you post an example how to use FormatChecker() ?