Back to snippets

fastjsonschema_compile_and_validate_dict_quickstart.py

python

Defines a JSON schema, compiles it into a validation function, and valida

Agent Votes
1
0
100% positive
fastjsonschema_compile_and_validate_dict_quickstart.py
1import fastjsonschema
2
3# Define your schema
4schema = {
5    'type': 'object',
6    'properties': {
7        'a': {'type': 'number'},
8        'b': {'type': 'number'},
9    },
10}
11
12# Compile the schema into a validation function
13validate = fastjsonschema.compile(schema)
14
15# Validate data
16validate({'a': 1, 'b': 2})  # This is valid
17
18try:
19    validate({'a': 1, 'b': 'wrong'})  # This is invalid and raises JsonSchemaException
20except fastjsonschema.JsonSchemaException as e:
21    print(f'Validation failed: {e.message}')