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

View resolved schema using RefResolver #802

Closed
anuj9196 opened this issue Apr 19, 2021 · 1 comment
Closed

View resolved schema using RefResolver #802

anuj9196 opened this issue Apr 19, 2021 · 1 comment

Comments

@anuj9196
Copy link

As per my use case, there are multiple schema files to validate against, based on the category to validate. Each category schema has multiple common components which are referenced in the schema using the $ref property.

In order to validate the data, I use the RefResolver to resolve the $ref properties across multiple subschema files.

In few cases, I need to know the final schema for a category, resolved using RefResolver that was used to validate the data.

How can I print the resolved schema ($ref replaced) after using the RefResolver?

My basic implementation is

class SchemaValidator:
    def __init__(self, category: str):
        self.category = category
        self.data = ''
        self.schema_path = os.path.join(os.path.dirname(__file__), 'json_schema', 'categories')

    def _schema(self):
        schema_file = self.category.replace(' ', '_')
        schema_path = os.path.join(self.schema_path, '{}.json'.format(schema_file))

        try:
            with open(schema_path, 'r') as file:
                return json.loads(file.read())
        except FileNotFoundError:
            raise Exception('Schema definition missing')
        except JSONDecodeError:
            raise Exception('Schema definition invalid')

    def _get_resolver(self):
        resolver = jsonschema.RefResolver(
            referrer=self._schema(),
            base_uri='file://{}/'.format(self.schema_path)
        )

        return resolver

    def validate(self, data):
        data = json.loads(data)

        return jsonschema.validators.Draft7Validator(
            self._schema(),
            resolver=self._get_resolver()
        ).validate(data)
@Julian
Copy link
Member

Julian commented Apr 19, 2021

Hi. I believe this is a duplicate of python-jsonschema/referencing#2. (PRs definitely welcome).

@Julian Julian closed this as completed Apr 19, 2021
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