marksparkza / jschon

An object-oriented JSON Schema implementation for Python.
https://jschon.readthedocs.io
MIT License
138 stars 13 forks source link

Modify error message for enum #36

Open BenjixLeGaulois opened 2 years ago

BenjixLeGaulois commented 2 years ago

Hi,

Would it be possible to modify the error message in the case of enum type? In case of a value not in the list of allowed possibilities, I would like to be able to embed suggestions in the error message using the levenshtein distance, like "Did you mean ...?" Please can you suggest a way of doing this, if possible? Many thanks.

marksparkza commented 2 years ago

Currently there's no supported / documented way to do this - I have some ideas about customizing behaviours, messages, etc for predefined keywords, but nothing concrete as yet.

However, the following approach should work - replace the existing EnumKeyword class in the meta-schema with your own enum keyword implementation:

from jschon import JSON, JSONSchema, URI, create_catalog
from jschon.jsonschema import Result
from jschon.vocabulary import Keyword

class MyEnumKeyword(Keyword):
    key = "enum"

    def evaluate(self, instance: JSON, result: Result) -> None:
        if instance not in self.json:
            result.fail(f'{instance} is not in {self.json}. Did you mean...')

catalog = create_catalog('2020-12')

metaschema = catalog.get_schema(URI('https://json-schema.org/draft/2020-12/schema'))
metaschema.kwclasses['enum'] = MyEnumKeyword

schema = JSONSchema({
    '$schema': 'https://json-schema.org/draft/2020-12/schema',
    'enum': ['foo', 'bar'],
})
data = JSON('baz')

print(schema.evaluate(data).output('basic'))