Python JSON and XML Schema Validation
Schema validation in Python is used to verify whether JSON and XML data follow a predefined structure, data types, mandatory fields, and validation rules.
Python provides different libraries for validating JSON and XML documents.
JSON Schema Validation in Python
JSON Schema validation checks whether JSON data follows a predefined schema.
To validate a JSON schema in Python, use the industry-standard jsonschema library.
First, install the library:
pip install jsonschema
Basic Validation (Quick Check)
Use the validate() function. If the data is valid, it returns nothing; if the data violates the schema, it raises a ValidationError.
import jsonschema from jsonschema import validate # 1. Define your JSON schema schema = { "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer", "minimum": 0} }, "required": ["name", "age"], "additionalProperties": False } # 2. Define data to test valid_data = {"name": "Alice", "age": 30} invalid_data = {"name": "Bob", "age": -5} # Fails 'minimum' constraint # 3. Validate try: validate(instance=valid_data, schema=schema) print("Valid data passed!") validate(instance=invalid_data, schema=schema) except jsonschema.exceptions.ValidationError as e: print(f"Validation failed: {e.message}")
XML Schema Validation in Python
The xmlschema Library (Recommended for Simplicity & XSD 1.1)
The xmlschema package is a pure Python library designed specifically for this purpose. It provides built-in support for both XSD 1.0 and XSD 1.1.
Installation:
pip install xmlschema
Example :
import xmlschema # 1. Load the XSD schema file # Note: For XSD 1.1 schemas, use xmlschema.XMLSchema11() instead schema = xmlschema.XMLSchema('schema.xsd') # Method A: Get a simple Boolean result (True/False) is_valid = schema.is_valid('document.xml') print(f"Is XML valid? {is_valid}") # Method B: Validate and catch specific structural errors try: schema.validate('document.xml') print("XML is valid!") except xmlschema.XMLSchemaValidationError as e: print(f"XML Validation failed: {e}")

No comments:
Post a Comment