pykwalify - JSON/YAML Schema Validator

1.8.0 · active · verified Thu Apr 09

pykwalify is a Python library and CLI tool for validating JSON and YAML data against a schema, based on the Kwalify schema specification. The current version is 1.8.0, with releases occurring periodically to add features, fix bugs, and update dependencies, though major development seems to have slowed since late 2020.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a schema and validate YAML data using pykwalify. It uses `io.StringIO` to simulate file input, making the example self-contained. It also shows how to catch `ValidationError` exceptions for invalid data.

import io
from pykwalify.core import Core, ValidationError

# Define your schema in YAML
schema_yaml = """
type: map
mapping:
  name:
    type: str
    required: true
  age:
    type: int
    range: {min: 0, max: 120}
    required: false
"""

# Define your data in YAML
data_yaml = """
name: Alice
age: 30
"""

# Create Core instance with StringIO objects for schema and data
c = Core(source_data=io.StringIO(data_yaml), schema_data=io.StringIO(schema_yaml))

try:
    c.validate()
    print("Validation successful!")
except ValidationError as e:
    print(f"Validation failed: {e}")

# Example of invalid data
invalid_data_yaml = """
name: Bob
age: 150
"""
c_invalid = Core(source_data=io.StringIO(invalid_data_yaml), schema_data=io.StringIO(schema_yaml))

try:
    c_invalid.validate()
except ValidationError as e:
    print(f"Invalid data validation failed as expected: {e}")

view raw JSON →