json-schema-parser 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- json_schema_parser/__init__.py +1 -0
- json_schema_parser/data_types.py +159 -0
- json_schema_parser/src.py +358 -0
- json_schema_parser-1.0.0.dist-info/METADATA +100 -0
- json_schema_parser-1.0.0.dist-info/RECORD +8 -0
- json_schema_parser-1.0.0.dist-info/WHEEL +5 -0
- json_schema_parser-1.0.0.dist-info/licenses/LICENSE +21 -0
- json_schema_parser-1.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from json_schema_parser.src import JsonSchemaParser
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import datetime
|
|
2
|
+
from enum import Enum
|
|
3
|
+
from typing import Any, List, Optional, Type, Union, get_args
|
|
4
|
+
from uuid import UUID
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class DataType(str, Enum):
|
|
8
|
+
INTEGER = "integer"
|
|
9
|
+
LIST_INTEGER = "integer[]"
|
|
10
|
+
OPTIONAL_INTEGER = "integer?"
|
|
11
|
+
OPTIONAL_LIST_INTEGER = "integer[]?"
|
|
12
|
+
|
|
13
|
+
FLOAT = "float"
|
|
14
|
+
LIST_FLOAT = "float[]"
|
|
15
|
+
OPTIONAL_FLOAT = "float?"
|
|
16
|
+
OPTIONAL_LIST_FLOAT = "float[]?"
|
|
17
|
+
|
|
18
|
+
STRING = "string"
|
|
19
|
+
LIST_STRING = "string[]"
|
|
20
|
+
OPTIONAL_STRING = "string?"
|
|
21
|
+
OPTIONAL_LIST_STRING = "string[]?"
|
|
22
|
+
|
|
23
|
+
BOOLEAN = "boolean"
|
|
24
|
+
LIST_BOOLEAN = "boolean[]"
|
|
25
|
+
OPTIONAL_BOOLEAN = "boolean?"
|
|
26
|
+
OPTIONAL_LIST_BOOLEAN = "boolean[]?"
|
|
27
|
+
|
|
28
|
+
JSON = "json"
|
|
29
|
+
LIST_JSON = "json[]"
|
|
30
|
+
OPTIONAL_JSON = "json?"
|
|
31
|
+
OPTIONAL_LIST_JSON = "json[]?"
|
|
32
|
+
|
|
33
|
+
UUID = "uuid"
|
|
34
|
+
LIST_UUID = "uuid[]"
|
|
35
|
+
OPTIONAL_UUID = "uuid?"
|
|
36
|
+
OPTIONAL_LIST_UUID = "uuid[]?"
|
|
37
|
+
|
|
38
|
+
DATETIME = "datetime"
|
|
39
|
+
LIST_DATETIME = "datetime[]"
|
|
40
|
+
OPTIONAL_DATETIME = "datetime?"
|
|
41
|
+
OPTIONAL_LIST_DATETIME = "datetime[]?"
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def is_many(self) -> bool:
|
|
45
|
+
return "[]" in self.value
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def is_optional(self) -> bool:
|
|
49
|
+
return "?" in self.value
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
PRIMITIVE_TYPES_DICT = {
|
|
53
|
+
DataType.INTEGER: int,
|
|
54
|
+
DataType.OPTIONAL_INTEGER: Optional[int],
|
|
55
|
+
DataType.FLOAT: float,
|
|
56
|
+
DataType.OPTIONAL_FLOAT: Optional[float],
|
|
57
|
+
DataType.STRING: str,
|
|
58
|
+
DataType.OPTIONAL_STRING: Optional[str],
|
|
59
|
+
DataType.BOOLEAN: bool,
|
|
60
|
+
DataType.OPTIONAL_BOOLEAN: Optional[bool],
|
|
61
|
+
DataType.DATETIME: datetime.datetime,
|
|
62
|
+
DataType.OPTIONAL_DATETIME: Optional[datetime.datetime],
|
|
63
|
+
DataType.UUID: UUID,
|
|
64
|
+
DataType.OPTIONAL_UUID: Optional[UUID]
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
ITERABLE_PRIMITIVE_TYPES_DICT = {
|
|
68
|
+
DataType.LIST_INTEGER: List[int],
|
|
69
|
+
DataType.OPTIONAL_LIST_INTEGER: Optional[List[int]],
|
|
70
|
+
DataType.LIST_FLOAT: List[float],
|
|
71
|
+
DataType.OPTIONAL_LIST_FLOAT: Optional[List[float]],
|
|
72
|
+
DataType.LIST_STRING: List[str],
|
|
73
|
+
DataType.OPTIONAL_LIST_STRING: Optional[List[str]],
|
|
74
|
+
DataType.LIST_BOOLEAN: List[bool],
|
|
75
|
+
DataType.OPTIONAL_LIST_BOOLEAN: Optional[List[bool]],
|
|
76
|
+
DataType.LIST_DATETIME: List[datetime.datetime],
|
|
77
|
+
DataType.OPTIONAL_LIST_DATETIME: Optional[List[datetime.datetime]],
|
|
78
|
+
DataType.LIST_UUID: List[UUID],
|
|
79
|
+
DataType.OPTIONAL_LIST_UUID: Optional[List[UUID]],
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
COMPLEX_TYPES_DICT = {
|
|
83
|
+
DataType.JSON: dict,
|
|
84
|
+
DataType.LIST_JSON: List[dict],
|
|
85
|
+
DataType.OPTIONAL_JSON: Optional[dict],
|
|
86
|
+
DataType.OPTIONAL_LIST_JSON: Optional[List[dict]],
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
FULL_PRIMITIVE_TYPES_DICT = {
|
|
90
|
+
**PRIMITIVE_TYPES_DICT,
|
|
91
|
+
**ITERABLE_PRIMITIVE_TYPES_DICT,
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
PYTHON_TYPES_DICT = {
|
|
95
|
+
**FULL_PRIMITIVE_TYPES_DICT,
|
|
96
|
+
**COMPLEX_TYPES_DICT,
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
PRIMITIVE_TO_DATA_TYPE_LOOKUP = {
|
|
100
|
+
value: key
|
|
101
|
+
for key, value in PYTHON_TYPES_DICT.items()
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def __extract_primitive_type(typing: Type | Union[Type, None]) -> Type | Union[Type, None]:
|
|
106
|
+
|
|
107
|
+
extracted_args = get_args(typing)
|
|
108
|
+
extracted_arg = extracted_args[0] if extracted_args else None
|
|
109
|
+
|
|
110
|
+
return typing if not extracted_arg else __extract_primitive_type(extracted_arg)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def extract_primitive_type(data_type: DataType) -> Any:
|
|
114
|
+
typing = PYTHON_TYPES_DICT[data_type]
|
|
115
|
+
return __extract_primitive_type(typing)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def is_default_value_valid(value: Any, data_type: DataType) -> bool:
|
|
119
|
+
if value is ...: # Ellipsis means "required / no default" — always valid
|
|
120
|
+
return True
|
|
121
|
+
PrimitiveType = extract_primitive_type(data_type)
|
|
122
|
+
if data_type.is_many:
|
|
123
|
+
# if value is list of JSON then optional value should be list or None.
|
|
124
|
+
if data_type == DataType.OPTIONAL_LIST_JSON:
|
|
125
|
+
return (isinstance(value, list) and len(value) == 0) or value is None
|
|
126
|
+
|
|
127
|
+
return isinstance(value, list) and all(
|
|
128
|
+
isinstance(item, (PrimitiveType, type(None))) for item in value
|
|
129
|
+
)
|
|
130
|
+
else:
|
|
131
|
+
# if value is JSON then optional value should be None.
|
|
132
|
+
if data_type == DataType.OPTIONAL_JSON:
|
|
133
|
+
return value is None
|
|
134
|
+
|
|
135
|
+
return isinstance(value, (PrimitiveType, type(None)))
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def get_default_value(data_type: DataType, default_value: Any) -> Any:
|
|
139
|
+
# TODO: Adjust flow for validation before getting default value.
|
|
140
|
+
if default_value is None:
|
|
141
|
+
return None if data_type.is_optional else ...
|
|
142
|
+
|
|
143
|
+
PrimitiveType = extract_primitive_type(data_type)
|
|
144
|
+
|
|
145
|
+
data_type_coersion_constructor_lookup = {
|
|
146
|
+
datetime.datetime: datetime.datetime.fromisoformat,
|
|
147
|
+
UUID: UUID,
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
if PrimitiveType in data_type_coersion_constructor_lookup:
|
|
151
|
+
Constructor = data_type_coersion_constructor_lookup[PrimitiveType]
|
|
152
|
+
if data_type.is_many:
|
|
153
|
+
return [
|
|
154
|
+
Constructor(item) if item is not None else None
|
|
155
|
+
for item in default_value
|
|
156
|
+
]
|
|
157
|
+
return Constructor(default_value)
|
|
158
|
+
|
|
159
|
+
return default_value
|
|
@@ -0,0 +1,358 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from typing import Any, Dict, Tuple, Type, Union, Literal, Optional, List, cast, get_args, get_origin
|
|
3
|
+
from functools import singledispatchmethod
|
|
4
|
+
from uuid import UUID
|
|
5
|
+
|
|
6
|
+
from pydantic import BaseModel, ConfigDict, Field, RootModel, field_validator, model_validator, create_model
|
|
7
|
+
from pydantic_core import PydanticUndefined
|
|
8
|
+
from pydantic.fields import FieldInfo
|
|
9
|
+
|
|
10
|
+
from json_schema_parser.data_types import (
|
|
11
|
+
PRIMITIVE_TO_DATA_TYPE_LOOKUP,
|
|
12
|
+
DataType,
|
|
13
|
+
PYTHON_TYPES_DICT,
|
|
14
|
+
is_default_value_valid,
|
|
15
|
+
get_default_value
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
# Type alias for Pydantic model types
|
|
19
|
+
PydanticModelType = Type[RootModel]
|
|
20
|
+
PydanticModel = BaseModel
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class SimpleTypeInput(BaseModel):
|
|
24
|
+
"""
|
|
25
|
+
this class represents the simple type structure of the json schema input
|
|
26
|
+
"""
|
|
27
|
+
model_config = ConfigDict(
|
|
28
|
+
extra='forbid'
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
field_type: Literal[
|
|
32
|
+
DataType.INTEGER,
|
|
33
|
+
DataType.STRING,
|
|
34
|
+
DataType.BOOLEAN,
|
|
35
|
+
DataType.FLOAT,
|
|
36
|
+
DataType.JSON,
|
|
37
|
+
DataType.DATETIME,
|
|
38
|
+
DataType.UUID
|
|
39
|
+
]
|
|
40
|
+
is_many: bool = False
|
|
41
|
+
is_optional: bool = False
|
|
42
|
+
field_default_value: Any = None
|
|
43
|
+
description: str = ""
|
|
44
|
+
|
|
45
|
+
@field_validator('field_type', mode='before')
|
|
46
|
+
def validate_field_type(cls, value):
|
|
47
|
+
return DataType(value)
|
|
48
|
+
|
|
49
|
+
@model_validator(mode='after')
|
|
50
|
+
def validate_field_default_value(self):
|
|
51
|
+
if not is_default_value_valid(self.default_value, self.data_type):
|
|
52
|
+
raise Exception(
|
|
53
|
+
f"Default value {self.default_value} is invalid for {self.field_type}.")
|
|
54
|
+
return self
|
|
55
|
+
|
|
56
|
+
@property
|
|
57
|
+
def primitive_type(self) -> Type:
|
|
58
|
+
python_type = PYTHON_TYPES_DICT[self.data_type]
|
|
59
|
+
return python_type
|
|
60
|
+
|
|
61
|
+
@property
|
|
62
|
+
def data_type(self) -> DataType:
|
|
63
|
+
field_type = self.field_type
|
|
64
|
+
field_type_value = field_type.value
|
|
65
|
+
|
|
66
|
+
if self.is_many:
|
|
67
|
+
field_type_value += '[]'
|
|
68
|
+
if self.is_optional:
|
|
69
|
+
field_type_value += '?'
|
|
70
|
+
|
|
71
|
+
data_type = DataType(field_type_value)
|
|
72
|
+
|
|
73
|
+
return data_type
|
|
74
|
+
|
|
75
|
+
@property
|
|
76
|
+
def default_value(self):
|
|
77
|
+
default_value = get_default_value(
|
|
78
|
+
self.data_type, self.field_default_value)
|
|
79
|
+
return default_value
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def pydantic_field(self) -> Tuple[Type, FieldInfo]:
|
|
83
|
+
return (self.primitive_type, Field(self.default_value, description=self.description))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class ComplexTypeInput(
|
|
87
|
+
RootModel[
|
|
88
|
+
Dict[
|
|
89
|
+
str,
|
|
90
|
+
Union[
|
|
91
|
+
'ComplexTypeInput',
|
|
92
|
+
'SimpleTypeInput'
|
|
93
|
+
]
|
|
94
|
+
]
|
|
95
|
+
]
|
|
96
|
+
):
|
|
97
|
+
"""
|
|
98
|
+
this class represents the complex type structure of the json input
|
|
99
|
+
which is a dictionary that map the name of the property and the type of it.
|
|
100
|
+
the type of the property could be SimpleTypeInput or ComplexTypeInput
|
|
101
|
+
The Request Body will look like so:
|
|
102
|
+
{
|
|
103
|
+
"optional_string_list": {
|
|
104
|
+
"field_type": "string",
|
|
105
|
+
"is_many": True,
|
|
106
|
+
"is_optional": True,
|
|
107
|
+
"field_default_value": [],
|
|
108
|
+
"description": "Optional string list"
|
|
109
|
+
},
|
|
110
|
+
"required_integer": {
|
|
111
|
+
"field_type": "integer",
|
|
112
|
+
"is_many": False,
|
|
113
|
+
"is_optional": False,
|
|
114
|
+
"field_default_value": None,
|
|
115
|
+
"description": "Required integer"
|
|
116
|
+
},
|
|
117
|
+
"nested_object": {
|
|
118
|
+
"__config": {
|
|
119
|
+
"field_type": "json",
|
|
120
|
+
"is_many": False,
|
|
121
|
+
"is_optional": False,
|
|
122
|
+
"field_default_value": None,
|
|
123
|
+
"description": "Nested object"
|
|
124
|
+
},
|
|
125
|
+
"nested_string": {
|
|
126
|
+
"field_type": "string",
|
|
127
|
+
"is_many": False,
|
|
128
|
+
"is_optional": False,
|
|
129
|
+
"field_default_value": None,
|
|
130
|
+
"description": "nested string",
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
"nested_object_list": {
|
|
134
|
+
"__config": {
|
|
135
|
+
"field_type": "json",
|
|
136
|
+
"is_many": True,
|
|
137
|
+
"is_optional": False,
|
|
138
|
+
"field_default_value": None,
|
|
139
|
+
"description": "Nested object"
|
|
140
|
+
},
|
|
141
|
+
"nested_string": {
|
|
142
|
+
"field_type": "string",
|
|
143
|
+
"is_many": False,
|
|
144
|
+
"is_optional": False,
|
|
145
|
+
"field_default_value": None,
|
|
146
|
+
"description": "nested string",
|
|
147
|
+
}
|
|
148
|
+
},
|
|
149
|
+
"__config": {
|
|
150
|
+
"field_type": "json",
|
|
151
|
+
"is_many": False,
|
|
152
|
+
"is_optional": False,
|
|
153
|
+
"field_default_value": None,
|
|
154
|
+
"description": "key description"
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
"""
|
|
158
|
+
|
|
159
|
+
@property
|
|
160
|
+
def config(self) -> SimpleTypeInput:
|
|
161
|
+
return cast(SimpleTypeInput, self.root['__config'])
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
class JsonSchemaParser(RootModel[
|
|
165
|
+
Union[
|
|
166
|
+
SimpleTypeInput,
|
|
167
|
+
ComplexTypeInput
|
|
168
|
+
]
|
|
169
|
+
]):
|
|
170
|
+
model_config = ConfigDict(
|
|
171
|
+
arbitrary_types_allowed=True
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
__is_simple_type: Optional[bool] = None # type: ignore
|
|
175
|
+
__pydantic_model: Optional[PydanticModelType] = None # type: ignore
|
|
176
|
+
|
|
177
|
+
# this function will be automaticaly executed after pydantic finishing the class initialization
|
|
178
|
+
def model_post_init(self, __context: dict) -> None:
|
|
179
|
+
self.__is_simple_type = isinstance(self.root, SimpleTypeInput)
|
|
180
|
+
|
|
181
|
+
@property
|
|
182
|
+
def is_simple_type(self) -> bool:
|
|
183
|
+
if self.__is_simple_type is None:
|
|
184
|
+
raise Exception("The model post init hasn't been executed yet.")
|
|
185
|
+
return self.__is_simple_type
|
|
186
|
+
|
|
187
|
+
@property
|
|
188
|
+
def simple_type(self) -> Type:
|
|
189
|
+
if self.__is_simple_type is False:
|
|
190
|
+
raise Exception(
|
|
191
|
+
"The generated model doesn't represent a simple type")
|
|
192
|
+
return cast(SimpleTypeInput, self.root).primitive_type
|
|
193
|
+
|
|
194
|
+
@singledispatchmethod
|
|
195
|
+
def __generate_pydantic_model(self, schema, model_name: str) -> PydanticModelType:
|
|
196
|
+
raise NotImplementedError(
|
|
197
|
+
f"No overloaded method defined for {type(schema)}")
|
|
198
|
+
|
|
199
|
+
@__generate_pydantic_model.register(SimpleTypeInput)
|
|
200
|
+
def _(self, schema: SimpleTypeInput, model_name: str) -> PydanticModelType:
|
|
201
|
+
schema_type = schema.primitive_type
|
|
202
|
+
if schema.is_many:
|
|
203
|
+
schema_type = List[schema_type]
|
|
204
|
+
if schema.is_optional:
|
|
205
|
+
schema_type = Optional[schema_type]
|
|
206
|
+
return RootModel[schema_type]
|
|
207
|
+
|
|
208
|
+
@__generate_pydantic_model.register(ComplexTypeInput)
|
|
209
|
+
def _(self, schema: ComplexTypeInput, model_name: str) -> PydanticModelType:
|
|
210
|
+
fields = {}
|
|
211
|
+
config = schema.config
|
|
212
|
+
|
|
213
|
+
for key, value in schema.root.items():
|
|
214
|
+
if key == '__config':
|
|
215
|
+
continue
|
|
216
|
+
|
|
217
|
+
inner_model = self.__generate_pydantic_model(value, key)
|
|
218
|
+
default_value = (
|
|
219
|
+
value.default_value if isinstance(value, SimpleTypeInput)
|
|
220
|
+
else value.config.default_value
|
|
221
|
+
)
|
|
222
|
+
is_optional = (
|
|
223
|
+
value.is_optional if isinstance(value, SimpleTypeInput)
|
|
224
|
+
else value.config.is_optional
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
fields[key] = (
|
|
228
|
+
inner_model,
|
|
229
|
+
... if not is_optional else default_value
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
created_model = create_model(model_name, **fields)
|
|
233
|
+
|
|
234
|
+
if config.is_many:
|
|
235
|
+
created_model = List[created_model]
|
|
236
|
+
if config.is_optional:
|
|
237
|
+
created_model = Optional[created_model]
|
|
238
|
+
|
|
239
|
+
created_model = RootModel[created_model]
|
|
240
|
+
|
|
241
|
+
return created_model
|
|
242
|
+
|
|
243
|
+
def generate_pydantic_model(self, model_name: str) -> PydanticModelType:
|
|
244
|
+
if self.__pydantic_model is None:
|
|
245
|
+
created_model = self.__generate_pydantic_model(
|
|
246
|
+
self.root, model_name)
|
|
247
|
+
self.__pydantic_model = created_model
|
|
248
|
+
return self.__pydantic_model
|
|
249
|
+
|
|
250
|
+
@staticmethod
|
|
251
|
+
def __json_schema_parse_default_values(value: Any) -> Any:
|
|
252
|
+
value = value() if callable(value) else value
|
|
253
|
+
|
|
254
|
+
is_list = isinstance(value, list)
|
|
255
|
+
values = value if is_list else [value]
|
|
256
|
+
|
|
257
|
+
if values and isinstance(values[0], (datetime, UUID)):
|
|
258
|
+
values = [
|
|
259
|
+
str(entry)
|
|
260
|
+
for entry in values
|
|
261
|
+
]
|
|
262
|
+
|
|
263
|
+
if is_list:
|
|
264
|
+
return values
|
|
265
|
+
|
|
266
|
+
return values[0]
|
|
267
|
+
|
|
268
|
+
@staticmethod
|
|
269
|
+
def __generate_json_schema_from_data_type(
|
|
270
|
+
primitive_type: Type,
|
|
271
|
+
description: str = "",
|
|
272
|
+
field_default_value: Any = None
|
|
273
|
+
) -> Dict[str, Any]:
|
|
274
|
+
|
|
275
|
+
config = {
|
|
276
|
+
"field_type": None,
|
|
277
|
+
"is_many": False,
|
|
278
|
+
"is_optional": False,
|
|
279
|
+
"description": description,
|
|
280
|
+
"field_default_value": field_default_value
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
is_primitive_type_nested = True
|
|
284
|
+
while is_primitive_type_nested:
|
|
285
|
+
typing_wrapper = get_origin(primitive_type)
|
|
286
|
+
if typing_wrapper:
|
|
287
|
+
is_primitive_type_nested = True
|
|
288
|
+
if typing_wrapper == Union:
|
|
289
|
+
config["is_optional"] = True
|
|
290
|
+
elif typing_wrapper == list:
|
|
291
|
+
config["is_many"] = True
|
|
292
|
+
primitive_type = get_args(primitive_type)[0]
|
|
293
|
+
else:
|
|
294
|
+
is_primitive_type_nested = False
|
|
295
|
+
try:
|
|
296
|
+
simple_data_type = PRIMITIVE_TO_DATA_TYPE_LOOKUP.get(
|
|
297
|
+
primitive_type)
|
|
298
|
+
except Exception:
|
|
299
|
+
simple_data_type = None
|
|
300
|
+
|
|
301
|
+
# Simple types.
|
|
302
|
+
if simple_data_type:
|
|
303
|
+
config["field_type"] = simple_data_type.value
|
|
304
|
+
|
|
305
|
+
# Complex types.
|
|
306
|
+
else:
|
|
307
|
+
config["field_type"] = DataType.JSON.value
|
|
308
|
+
config = {
|
|
309
|
+
"__config": config
|
|
310
|
+
}
|
|
311
|
+
for key, value in primitive_type.__fields__.items():
|
|
312
|
+
config[key] = JsonSchemaParser.__generate_json_schema_from_data_type(
|
|
313
|
+
value.annotation,
|
|
314
|
+
value.description,
|
|
315
|
+
None if value.default == PydanticUndefined else
|
|
316
|
+
JsonSchemaParser.__json_schema_parse_default_values(
|
|
317
|
+
value.default)
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
return config
|
|
321
|
+
|
|
322
|
+
@staticmethod
|
|
323
|
+
def generate_json_schema_from_data_type(primitive_type: Type) -> Dict[str, Any]:
|
|
324
|
+
"""
|
|
325
|
+
Generates a JSON schema representation from a given primitive data type.
|
|
326
|
+
This function converts a Python primitive type or a Pydantic model into a JSON schema
|
|
327
|
+
string that describes the data structure and its properties.
|
|
328
|
+
Args:
|
|
329
|
+
primitive_type (Type): The primitive type or Pydantic model to convert to JSON schema.
|
|
330
|
+
Can be a basic Python type (str, int, etc.) or a Pydantic model class.
|
|
331
|
+
Returns:
|
|
332
|
+
str: A JSON string representing the schema of the input type, including:
|
|
333
|
+
- field_type: The base data type
|
|
334
|
+
- is_many: Boolean indicating if it's a collection
|
|
335
|
+
- is_optional: Boolean indicating if the field is optional
|
|
336
|
+
- description: Field description string
|
|
337
|
+
- field_default_value: Default value if any
|
|
338
|
+
For Pydantic models, returns nested schema with __config and field definitions.
|
|
339
|
+
Example:
|
|
340
|
+
>>> generate_json_schema_from_data_type(str)
|
|
341
|
+
{
|
|
342
|
+
"field_type": "STRING",
|
|
343
|
+
"is_many": false,
|
|
344
|
+
"is_optional": false,
|
|
345
|
+
"description": "",
|
|
346
|
+
"field_default_value": null
|
|
347
|
+
}
|
|
348
|
+
"""
|
|
349
|
+
return JsonSchemaParser.__generate_json_schema_from_data_type(primitive_type)
|
|
350
|
+
|
|
351
|
+
def is_empty(self) -> bool:
|
|
352
|
+
"""Checks if the JSON schema represents an empty structure (i.e., no fields defined).
|
|
353
|
+
"""
|
|
354
|
+
if self.is_simple_type:
|
|
355
|
+
return False
|
|
356
|
+
else:
|
|
357
|
+
complex_root = cast(ComplexTypeInput, self.root)
|
|
358
|
+
return complex_root.root == {}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: json-schema-parser
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Convert between JSON schema definitions and Pydantic models
|
|
5
|
+
Home-page: https://github.com/24torky/json-schema-parser
|
|
6
|
+
Author: Abdelrahman Torky
|
|
7
|
+
Author-email: 24torky@gmail.com
|
|
8
|
+
License: MIT
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Operating System :: OS Independent
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Requires-Dist: pydantic>=2.0
|
|
21
|
+
Dynamic: author
|
|
22
|
+
Dynamic: author-email
|
|
23
|
+
Dynamic: classifier
|
|
24
|
+
Dynamic: description
|
|
25
|
+
Dynamic: description-content-type
|
|
26
|
+
Dynamic: home-page
|
|
27
|
+
Dynamic: license
|
|
28
|
+
Dynamic: license-file
|
|
29
|
+
Dynamic: requires-dist
|
|
30
|
+
Dynamic: requires-python
|
|
31
|
+
Dynamic: summary
|
|
32
|
+
|
|
33
|
+
# json-schema-parser
|
|
34
|
+
|
|
35
|
+
A Python library for converting between JSON schema definitions and Pydantic models.
|
|
36
|
+
|
|
37
|
+
## Features
|
|
38
|
+
|
|
39
|
+
- Parse a JSON schema dict into a validated Pydantic model
|
|
40
|
+
- Generate a JSON schema dict from any Python type or Pydantic model
|
|
41
|
+
- Supports all common types: `integer`, `float`, `string`, `boolean`, `json`, `uuid`, `datetime`
|
|
42
|
+
- Supports list (`is_many`) and optional (`is_optional`) variants of every type
|
|
43
|
+
- Nested object schemas via `ComplexTypeInput`
|
|
44
|
+
|
|
45
|
+
## Installation
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
pip install json-schema-parser
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
## Usage
|
|
52
|
+
|
|
53
|
+
### Parse a JSON schema into a Pydantic model
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from json_schema_parser import JsonSchemaParser
|
|
57
|
+
|
|
58
|
+
schema = {
|
|
59
|
+
"__config": {"field_type": "json", "is_many": False, "is_optional": False, "field_default_value": None, "description": ""},
|
|
60
|
+
"name": {"field_type": "string", "is_many": False, "is_optional": False, "field_default_value": None, "description": "User name"},
|
|
61
|
+
"age": {"field_type": "integer", "is_many": False, "is_optional": True, "field_default_value": None, "description": "User age"},
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
parser = JsonSchemaParser.model_validate(schema)
|
|
65
|
+
Model = parser.generate_pydantic_model("User")
|
|
66
|
+
|
|
67
|
+
user = Model.model_validate({"name": "Alice", "age": 30})
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
### Generate a JSON schema from a Python type
|
|
71
|
+
|
|
72
|
+
```python
|
|
73
|
+
from json_schema_parser import JsonSchemaParser
|
|
74
|
+
from pydantic import BaseModel
|
|
75
|
+
from typing import Optional, List
|
|
76
|
+
|
|
77
|
+
class Address(BaseModel):
|
|
78
|
+
street: str
|
|
79
|
+
city: str
|
|
80
|
+
|
|
81
|
+
schema = JsonSchemaParser.generate_json_schema_from_data_type(Address)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
## Supported field types
|
|
85
|
+
|
|
86
|
+
| `field_type` value | Python type |
|
|
87
|
+
|---|---|
|
|
88
|
+
| `"integer"` | `int` |
|
|
89
|
+
| `"float"` | `float` |
|
|
90
|
+
| `"string"` | `str` |
|
|
91
|
+
| `"boolean"` | `bool` |
|
|
92
|
+
| `"uuid"` | `UUID` |
|
|
93
|
+
| `"datetime"` | `datetime` |
|
|
94
|
+
| `"json"` | `dict` / nested model |
|
|
95
|
+
|
|
96
|
+
Set `is_many: true` to get a `List[T]`, and `is_optional: true` to get `Optional[T]`.
|
|
97
|
+
|
|
98
|
+
## License
|
|
99
|
+
|
|
100
|
+
MIT
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
json_schema_parser/__init__.py,sha256=BABFpUI-WpEua__7fae6X9npFsiqgstdj_lFgIY7yGQ,52
|
|
2
|
+
json_schema_parser/data_types.py,sha256=ET8RxWVJlZt6zRivouKyZ95MHLXmoIUVm5uf4oOWQ5A,4796
|
|
3
|
+
json_schema_parser/src.py,sha256=HGsCfXVBfANcUr00WtbdEKKcU4K2VAbLBGphhmp7Vac,12065
|
|
4
|
+
json_schema_parser-1.0.0.dist-info/licenses/LICENSE,sha256=o2VYQtToy1kCZ5AHF1J_iOhbUUaAfdr2kGIBPcf51Hk,1074
|
|
5
|
+
json_schema_parser-1.0.0.dist-info/METADATA,sha256=QhwqtG294eXP6RONmEFkvTdx1KQac4U0VtsidlLkm2c,2915
|
|
6
|
+
json_schema_parser-1.0.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
7
|
+
json_schema_parser-1.0.0.dist-info/top_level.txt,sha256=MepYz5aBi7-J0Xvb5Iv_-QPeUXdCZJOd7myKGS-Bz18,19
|
|
8
|
+
json_schema_parser-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Abdelrahman Torky
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
json_schema_parser
|