Transform the pydantic schema into a more comprehensible JSON schema. Args: pydantic_schema (dict): The pydantic schema. Returns: dict: The transformed JSON schema.
(pydantic_schema)
| 4 | |
| 5 | |
| 6 | def transform_schema(pydantic_schema): |
| 7 | """ |
| 8 | Transform the pydantic schema into a more comprehensible JSON schema. |
| 9 | |
| 10 | Args: |
| 11 | pydantic_schema (dict): The pydantic schema. |
| 12 | |
| 13 | Returns: |
| 14 | dict: The transformed JSON schema. |
| 15 | """ |
| 16 | |
| 17 | def process_properties(properties): |
| 18 | result = {} |
| 19 | for key, value in properties.items(): |
| 20 | if "type" in value: |
| 21 | if value["type"] == "array": |
| 22 | if "items" in value and "$ref" in value["items"]: |
| 23 | ref_key = value["items"]["$ref"].split("/")[-1] |
| 24 | if "$defs" in pydantic_schema and ref_key in pydantic_schema["$defs"]: |
| 25 | result[key] = [ |
| 26 | process_properties( |
| 27 | pydantic_schema["$defs"][ref_key].get("properties", {}) |
| 28 | ) |
| 29 | ] |
| 30 | else: |
| 31 | result[key] = ["object"] # fallback for missing reference |
| 32 | elif "items" in value and "type" in value["items"]: |
| 33 | result[key] = [value["items"]["type"]] |
| 34 | else: |
| 35 | result[key] = ["unknown"] # fallback for malformed array |
| 36 | else: |
| 37 | result[key] = { |
| 38 | "type": value["type"], |
| 39 | "description": value.get("description", ""), |
| 40 | } |
| 41 | elif "$ref" in value: |
| 42 | ref_key = value["$ref"].split("/")[-1] |
| 43 | if "$defs" in pydantic_schema and ref_key in pydantic_schema["$defs"]: |
| 44 | result[key] = process_properties( |
| 45 | pydantic_schema["$defs"][ref_key].get("properties", {}) |
| 46 | ) |
| 47 | else: |
| 48 | result[key] = {"type": "object", "description": "Missing reference"} # fallback |
| 49 | return result |
| 50 | |
| 51 | if "properties" not in pydantic_schema: |
| 52 | raise ValueError("Invalid pydantic schema: missing 'properties' key") |
| 53 | return process_properties(pydantic_schema["properties"]) |
no test coverage detected