Describe the bug
When json schema includes an object with additionalProperties , the generated pydantic model doesn't contain __root__ attribute
To Reproduce
Example schema:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "test.json",
"description": "test",
"type": "object",
"required": [
"test_id",
"test_ip",
"result"
],
"properties": {
"test_id": {
"type": "string",
"description": "test ID"
},
"test_ip": {
"type": "string",
"description": "test IP"
},
"result": {
"type": "object",
"additionalProperties": {
"type": "integer"
}
}
}
}
Used commandline:
$ datamodel-codegen --input test.json --output model.py
Generated code from the schema:
from __future__ import annotations
from typing import Dict
from pydantic import BaseModel, Extra, Field
class Result(BaseModel):
pass
class Config:
extra = Extra.allow
class Model(BaseModel):
test_id: str = Field(..., description='test ID')
test_ip: str = Field(..., description='test IP')
result: Dict[str, Result]
When instantiating this class with the following code:
model = Model(test_id="test", test_ip="test", result={"a": 5})
The following error is raised from pydantic:
pydantic.error_wrappers.ValidationError: 1 validation error for Model
result -> a
value is not a valid dict (type=type_error.dict)
Expected behavior
The issue can be solved by adding __root__ atrribute to Result model:
class Result(BaseModel):
__root__: int
class Config:
extra = Extra.allow
Version:
Additional context
I have found the similar issue but solution works only for arrays:
"result": {
"type": "object",
"additionalProperties": {
"type": "array",
"items": {
"type": "integer"
}
}
}
@MikeZaharov
Thank you for creating this issue.
I confirmed this problem. I will fix it.
@MikeZaharov
I have released a fixed version as 0.6.24 馃殌
@koxudaxi
Thank you a lot for your quick response! The new version works as expected)
Most helpful comment
@koxudaxi
Thank you a lot for your quick response! The new version works as expected)