Programmatic (Python) format check in jsonschema

156 Views Asked by At

I have a schema where a property should comply to a pattern that only can be checked programmatically:

type: object
properties:
  unit:
    description: Unit of this column. Must be FITS conform.
    type: string

where "FITS conformity" can be ensured by a small Python snippet (which raises an exception on fail):

import astropy.units as u
u.Unit(col["unit"], format=u.format.Fits)

It seems that this could be done with a custom "format" attribute of the property:

type: object
properties:
  unit:
    description: Unit of this column. Must be FITS conform.
    type: string
    format: fitsunit

and then implement a format checker with the decorator jsonschema.FormatChecker.checks. However, I could not find out how to write this.

1

There are 1 best solutions below

0
olebole On BEST ANSWER

I finally found this out myself. The decorator is used for a simple checker function, that takes one single argument:

from jsonschema import validate, Draft202012Validator

@Draft202012Validator.FORMAT_CHECKER.checks("fitsunit", ValueError)
def check_fitsunit(s):
    import astropy.units as u
    u.Unit(s, format=u.format.Fits)
    return True

validate(my_file, my_schema, format_checker=Draft202012Validator.FORMAT_CHECKER)