Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pydantic.error_wrappers.ValidationError: 1 validation error for B

When I try to parse JSON object with Pydantic, my IDE returns error...

Code:

from pydantic import BaseModel, Field

class A(BaseModel):
    a: str = Field(None, alias="А")

class B(BaseModel):
    b: dict[str, A] = Field(None, alias="Б")

j = {
    "Б": {
        "А": "Значение"
    }
}

obj=B.parse_obj(j)

... and error text:

File "pydantic/main.py", line 572, in pydantic.main.BaseModel.parse_obj
  File "pydantic/main.py", line 400, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for B
Б -> А
  value is not a valid dict (type=type_error.dict)

please answer why this is happening

like image 783
Azat Avatar asked Apr 09 '26 13:04

Azat


1 Answers

Oh, it was so simple... instead of using a dict type, just use the model A, which already matches the subobject.

from pydantic import BaseModel, Field


class A(BaseModel):
    a: str = Field(None, alias="А")


class B(BaseModel):
    b: A = Field(None, alias="Б")


j = {
    "Б": {
        "А": "Значение"
    }
}

obj = B.parse_obj(j)
print(obj.json())
like image 148
Azat Avatar answered Apr 11 '26 02:04

Azat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!