Skip to content

Commit 7ed4480

Browse files
Better JSON-Schema output for Decimal (#692)
Co-authored-by: konstantin <konstantin.klein@hochfrequenz.de>
1 parent 9995dce commit 7ed4480

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

generate_or_validate_json_schemas.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@
1515

1616
import click
1717
from pydantic import BaseModel, TypeAdapter
18+
from pydantic.json_schema import GenerateJsonSchema as _GenerateJsonSchema
19+
from pydantic.json_schema import JsonSchemaValue
20+
from pydantic_core import core_schema
1821

1922
from bo4e import ZusatzAttribut
2023

@@ -34,6 +37,24 @@
3437
PARSABLE_CLASS_TYPE = type[BaseModel] | type[Enum]
3538

3639

40+
class GenerateJsonSchema(_GenerateJsonSchema):
41+
"""
42+
This class is a copy of pydantic.json_schema.GenerateJsonSchema with the only difference that the
43+
decimal_schema method is overwritten to generate a JSON schema that can be used by the
44+
BO4E-Python-Generator (https://github.com/bo4e/BO4E-Python-Generator).
45+
"""
46+
47+
def decimal_schema(self, schema: core_schema.DecimalSchema) -> JsonSchemaValue:
48+
"""
49+
Generates a JSON schema that matches a decimal value.
50+
The output format is changed to work well with BO4E-Python-Generator.
51+
"""
52+
json_schema = self.str_schema(core_schema.str_schema())
53+
if self.mode == "validation":
54+
json_schema["format"] = "decimal"
55+
return json_schema
56+
57+
3758
def delete_json_schemas(packages: list[str]) -> None:
3859
"""delete all json schemas"""
3960
for pkg in packages:
@@ -84,9 +105,9 @@ def get_schema_json_dict(cls: Any) -> dict[str, Any]:
84105
Get the json schema for a class
85106
"""
86107
if issubclass(cls, BaseModel):
87-
schema_json_dict = cls.model_json_schema()
108+
schema_json_dict = cls.model_json_schema(schema_generator=GenerateJsonSchema)
88109
elif issubclass(cls, Enum):
89-
schema_json_dict = TypeAdapter(cls).json_schema()
110+
schema_json_dict = TypeAdapter(cls).json_schema(schema_generator=GenerateJsonSchema)
90111
else:
91112
raise ValueError(f"Class {cls} is neither a pydantic BaseModel nor an enum.")
92113
if "$defs" in schema_json_dict:

0 commit comments

Comments
 (0)