从字符串列表中解析 Pydantic 类列表

Lon*_*Rob 4 python pydantic

我想用以下数据Polygon列表来解析 a :Points

{"points": ["0|0", "1|0", "1|1"]}
Run Code Online (Sandbox Code Playgroud)

我天真地以为我可以做这样的事情:

from pydantic import BaseModel, validator


class Point(BaseModel):
    x: int
    y: int

    @validator("x", "y", pre=True)
    def get_coords(cls, value, values):
        x, y = value.split("|")
        values["x"] = x
        values["y"] = y


class Polygon(BaseModel):
    points: list[Point]
Run Code Online (Sandbox Code Playgroud)

但是当我尝试解析我的“JSON”字符串时,我收到一条错误消息value is not a valid dict

>>> Polygon.parse_obj({"points": ["0|0", "1|0", "1|1"]})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "pydantic/main.py", line 511, in pydantic.main.BaseModel.parse_obj
  File "pydantic/main.py", line 331, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 3 validation errors for Polygon
points -> 0
  value is not a valid dict (type=type_error.dict)
points -> 1
  value is not a valid dict (type=type_error.dict)
points -> 2
  value is not a valid dict (type=type_error.dict)
Run Code Online (Sandbox Code Playgroud)

如何从这个枯燥的字符串列表中解析出有趣的对象?

Lon*_*Rob 6

这里我们需要克服的问题是Polygon.points获取的列表str 不是Point预期的列表;所以这是我们应该干预的地方:

from pydantic import BaseModel, validator


class Point(BaseModel):
    x: int
    y: int


class Polygon(BaseModel):
    points: list[Point]

    @validator("points", pre=True, each_item=True)
    def each_element_should_be_a_point(cls, v):
        coords = v.split("|")
        point = Point(x=coords[0], y=coords[1])
        return point


poly = Polygon.parse_obj({"points": ["0|0", "1|0", "1|1"]})
Run Code Online (Sandbox Code Playgroud)