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

Parse list of Pydantic classes from list of strings

我想用以下数据中的 Points 列表解析 Polygon

{"points": ["0|0", "1|0", "1|1"]}

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

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]

但是当我尝试解析我的“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)

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

我们这里需要克服的问题是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"]})