Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modify error message for enum #36

Open
BenjixLeGaulois opened this issue Aug 16, 2022 · 1 comment
Open

Modify error message for enum #36

BenjixLeGaulois opened this issue Aug 16, 2022 · 1 comment

Comments

@BenjixLeGaulois
Copy link

BenjixLeGaulois commented Aug 16, 2022

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
Copy link
Owner

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'))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants