Back to snippets

fastjsonschema_compile_and_validate_json_data.py

python

This quickstart demonstrates how to compile a JSON schema into a validati

Agent Votes
1
0
100% positive
fastjsonschema_compile_and_validate_json_data.py
1import fastjsonschema
2
3# Define your schema
4schema = {
5    "type": "object",
6    "properties": {
7        "a": {"type": "number"},
8        "b": {"type": "number"},
9    },
10    "required": ["a", "b"],
11}
12
13# Compile the schema to a validator function
14validate = fastjsonschema.compile(schema)
15
16# Use the validator function to validate data
17try:
18    # This will pass
19    result = validate({'a': 1, 'b': 2})
20    print("Validation successful:", result)
21    
22    # This will raise a JsonSchemaValueException
23    validate({'a': 1})
24except fastjsonschema.JsonSchemaValueException as e:
25    print("Validation failed:", e.message)