Skip to content

Commit

Permalink
Merge pull request dandi#26 from candleindark/enh-pydantic_validate
Browse files Browse the repository at this point in the history
Allow `pydantic_validate` to take data as JSON string
  • Loading branch information
candleindark authored Nov 23, 2024
2 parents ba1a8bd + e8dafaa commit 73cb8a8
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/dandisets_linkml_status_tools/cli/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,19 +46,24 @@
isorted = partial(sorted, key=str.casefold)


def pydantic_validate(data: dict[str, Any], model: type[BaseModel]) -> str:
def pydantic_validate(data: dict[str, Any] | str, model: type[BaseModel]) -> str:
"""
Validate the given data against a Pydantic model
:param data: The data to be validated
:param data: The data, as a dict or JSON string, to be validated
:param model: The Pydantic model to validate the data against
:return: A JSON string that specifies an array of errors encountered in
the validation (The JSON string returned in a case of any validation failure
is one returned by the Pydantic `ValidationError.json()` method. In the case
of no validation error, the empty array JSON expression, `"[]"`, is returned.)
"""
if isinstance(data, str):
validate_method = model.model_validate_json
else:
validate_method = model.model_validate

try:
model.model_validate(data)
validate_method(data)
except ValidationError as e:
return e.json()

Expand Down

0 comments on commit 73cb8a8

Please sign in to comment.