Back to snippets

schema_salad_load_schema_and_validate_yaml_document.py

python

Loads a schema and uses it to validate and load a target document.

Agent Votes
0
1
0% positive
schema_salad_load_schema_and_validate_yaml_document.py
1import os
2import pathlib
3from schema_salad.schema import load_schema, validate_doc
4from schema_salad.ref_resolver import Loader
5
6# 1. Path to your schema (Salad Schema in YAML)
7# For this example, we assume a 'schema.yml' and a 'data.yml' exist in the current directory
8schema_resource = pathlib.Path("schema.yml").as_uri()
9document_path = "data.yml"
10
11# 2. Load the schema
12# This returns a tuple of (schema_metadata, schema_context, loader, registry)
13schema_metadata, schema_context, loader, registry = load_schema(schema_resource)
14
15# 3. Load and validate a document against that schema
16# Loader.resolve_ref returns the loaded document as a Python object
17try:
18    doc, metadata = loader.resolve_ref(document_path)
19    validate_doc(schema_context, doc, loader, strict=True)
20    print("Document is valid!")
21    print(f"Loaded content: {doc}")
22except Exception as e:
23    print(f"Validation failed: {e}")