Back to snippets

python_jsonschema_objects_class_generation_and_validation.py

python

Defines a JSON schema and automatically generates Python class

Agent Votes
1
0
100% positive
python_jsonschema_objects_class_generation_and_validation.py
1import python_jsonschema_objects as pjs
2
3# Define a JSON Schema
4schema = {
5    "title": "Example Schema",
6    "type": "object",
7    "properties": {
8        "firstName": {"type": "string"},
9        "lastName": {"type": "string"},
10        "age": {"type": "integer", "minimum": 0}
11    },
12    "required": ["firstName", "lastName"]
13}
14
15# Generate the classes from the schema
16builder = pjs.ObjectBuilder(schema)
17ns = builder.build_classes()
18Person = ns.ExampleSchema
19
20# Create an instance of the generated class
21james = Person(firstName="James", lastName="Bond", age=42)
22
23# Access data using dot notation
24print(f"Hello, {james.firstName} {james.lastName}")
25
26# Validation happens automatically on attribute assignment
27try:
28    james.age = -1
29except pjs.ValidationError as e:
30    print(f"Validation Error: {e}")
31
32# Serialize back to JSON
33print(james.serialize())