Skip to content

Commit

Permalink
feat: Implement validate_json()
Browse files Browse the repository at this point in the history
A util func for validating a metadata
instance of a DANDI model against the
JSON schema of the model
  • Loading branch information
candleindark committed Jan 30, 2025
1 parent 47ad293 commit 5930e7f
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion dandischema/utils.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
from __future__ import annotations

import re
from typing import Any, Iterator, List, Union, get_args, get_origin
from typing import Any, Iterator, List, Union, cast, get_args, get_origin

from jsonschema import Draft7Validator, Draft202012Validator
from jsonschema.protocols import Validator as JsonschemaValidator
from jsonschema.validators import validator_for
from pydantic.json_schema import GenerateJsonSchema, JsonSchemaMode, JsonSchemaValue
from pydantic_core import CoreSchema, core_schema

from .exceptions import JsonschemaValidationError

TITLE_CASE_LOWER = {
"a",
"an",
Expand Down Expand Up @@ -176,3 +179,41 @@ def jsonschema_validator(

# Return a validator with format checking disabled
return validator_cls(schema)


def validate_json(instance: Any, schema: dict[str, Any]) -> None:
"""
Validate a metadata instance of a **DANDI model** against the JSON schema of the
model
:param instance: The metadata instance to validate
:param schema: The JSON schema of the model
:raises JsonschemaValidationError: If the metadata instance is invalid, an instance
of this exception containing a list of `jsonschema.exceptions.ValidationError`
instances representing all the errors detected in the validation is raised
:raises jsonschema.exceptions.SchemaError: If the JSON schema is invalid
:raises ValueError: If the schema does not contain a 'schemaVersion' field
"""
if "schemaVersion" not in schema:
raise ValueError("The schema must contain a 'schemaVersion' field")

default_validator_cls = cast(
type[JsonschemaValidator],
(
Draft202012Validator
# `"schemaVersion"` 0.6.5 and above is produced with Pydantic V2
# which is compliant with JSON Schema Draft 2020-12
if version2tuple(schema["schemaVersion"]) >= version2tuple("0.6.5")
else Draft7Validator
),
)

validator = jsonschema_validator(
schema, check_format=True, default_cls=default_validator_cls
)

errs = sorted(validator.iter_errors(instance), key=str)

if errs:
raise JsonschemaValidationError(errs)

0 comments on commit 5930e7f

Please sign in to comment.