Python jsonschema Validate Timezone

Viewed 257

Just wondering if there is a way to extend the FormatChecker that is passed to the jsonschema validator? I can't seem to find anything in the documentation. Basically, I am trying to check if a string value is a valid timezone. I'm using pytz for the timezone side. But, I need to check the provided json string property is contained within that list. The only other way I can think of is to extract the list as an enum field in the schema. But, it's a huge list and seems a pretty clunky way of doing it. Ideally, I'd like something like this:

from pytz import common_timezones
from jsonschema import validate, FormatChecker

timezone_checker = FormatChecker(formats=["timezone"])
timezone_checker.extend(check_timezone)

instance = { "timezone": "Australia/Sydney" }
schema = {
    "properties": {
        "timezone": {"type": "string", "format": "timezone"}
    }
}

validate(instance=instance, schema=schema, format_checker=timezone_checker)

...

def check_timezone(p):
    if not isinstance(p, str):
        return False
    return p in common_timezones

Thanks in advance.

1 Answers
Related