Skip to content

Commit d1bebc7

Browse files
committed
feat: provide helper func to create appropriate jsonschema validator
1 parent 6fd04fb commit d1bebc7

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

dandischema/utils.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
import re
44
from typing import Any, Iterator, List, Union, get_args, get_origin
55

6+
from jsonschema.protocols import Validator as JsonschemaValidator
7+
from jsonschema.validators import validator_for
68
from pydantic.json_schema import GenerateJsonSchema, JsonSchemaMode, JsonSchemaValue
79
from pydantic_core import CoreSchema, core_schema
810

@@ -136,3 +138,41 @@ def sanitize_value(value: str, field: str = "non-extension", sub: str = "-") ->
136138
if field != "extension":
137139
value = value.replace(".", sub)
138140
return value
141+
142+
143+
def jsonschema_validator(
144+
schema: dict[str, Any],
145+
*,
146+
check_format: bool,
147+
default_cls: type[JsonschemaValidator] | None = None,
148+
) -> JsonschemaValidator:
149+
"""
150+
Create a JSON schema validator appropriate for validating instances against a given
151+
schema
152+
153+
:param schema: The JSON schema to validate against
154+
:param check_format: Indicates whether to check the format against format
155+
specifications in the schema
156+
:param default_cls: The default JSON schema validator class to use to create the
157+
validator should the appropriate validator class cannot be determined based on
158+
the schema (by assessing the `$schema` property). If `None`, the class
159+
representing the latest JSON schema draft supported by the `jsonschema` package.
160+
:return: The JSON schema validator
161+
:raises jsonschema.exceptions.SchemaError: If the JSON schema is invalid
162+
"""
163+
# Retrieve appropriate validator class for validating the given schema
164+
validator_cls = (
165+
validator_for(schema, default_cls)
166+
if default_cls is not None
167+
else validator_for(schema)
168+
)
169+
170+
# Ensure the schema is valid
171+
validator_cls.check_schema(schema)
172+
173+
if check_format:
174+
# Return a validator with format checking enabled
175+
return validator_cls(schema, format_checker=validator_cls.FORMAT_CHECKER)
176+
177+
# Return a validator with format checking disabled
178+
return validator_cls(schema)

0 commit comments

Comments
 (0)