如何验证名称为 "from" 的 JSON 字段

How to validate JSON field with name "from"

我想验证 JSON 对象(它在 Telegram Bot API) which contains from field (which is reserved word in Python) by using pydantic 验证器中。所以我的模型应该如下所示:

class Message(BaseModel):
  message_id: int
  from: Optional[str]
  date: int
  chat: Any
  ...

但是在此上下文中不允许使用 from 关键字。

我该怎么做?

注意: 这与 "Why we can't use keywords as attributes" 不同 因为这里我们得到外部 JSON 我们没有控制,我们无论如何应该用 from 字段处理 JSON。

believe你可以用from_替换from

你可以这样做:

class Message(BaseModel):
    message_id: int
    from_: Optional[str]
    date: int
    chat: Any

    class Config:
        fields = {
        'from_': 'from'
        }
    ...

可能有一种方法可以使用 class 语句来执行此操作,但我在快速浏览文档时没有看到任何内容。您可以做的是改用动态模型创建。

fields = {
    'message_id': (int,),
    'from': (Optional[str], ...),
    'date': (int, ...),
    'chat': (Any, ...)
 }
 Message = create_model("Message", **fields)