Validate JSON text against a schema and return the result. Args: schema: The schema to validate against. json_text: The JSON text to validate. Returns: The validated result. Type depends on the schema: - dict for BaseModel - list of dicts for list[BaseModel] - raw
(schema: SchemaType, json_text: str)
| 107 | |
| 108 | |
| 109 | def validate_schema(schema: SchemaType, json_text: str) -> Any: |
| 110 | """Validate JSON text against a schema and return the result. |
| 111 | |
| 112 | Args: |
| 113 | schema: The schema to validate against. |
| 114 | json_text: The JSON text to validate. |
| 115 | |
| 116 | Returns: |
| 117 | The validated result. Type depends on the schema: |
| 118 | - dict for BaseModel |
| 119 | - list of dicts for list[BaseModel] |
| 120 | - raw value for other schema types (list[str], dict, etc.) |
| 121 | """ |
| 122 | if is_basemodel_schema(schema): |
| 123 | # For regular BaseModel, use model_validate_json |
| 124 | return schema.model_validate_json(json_text).model_dump(exclude_none=True) |
| 125 | elif is_list_of_basemodel(schema): |
| 126 | # For list[BaseModel], use TypeAdapter to validate |
| 127 | type_adapter = TypeAdapter(schema) |
| 128 | validated = type_adapter.validate_json(json_text) |
| 129 | return [item.model_dump(exclude_none=True) for item in validated] |
| 130 | else: |
| 131 | # For other schema types (list[str], dict, Schema, etc.), |
| 132 | # just parse JSON without pydantic validation |
| 133 | return json.loads(json_text) |