Skip to content

View resolved schema using RefResolver #802

@anuj9196

Description

@anuj9196

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions