Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何验证名为“的JSON字段”;从「;_Python_Json_Telegram Bot_Pydantic - Fatal编程技术网

Python 如何验证名为“的JSON字段”;从「;

Python 如何验证名为“的JSON字段”;从「;,python,json,telegram-bot,pydantic,Python,Json,Telegram Bot,Pydantic,我想通过使用验证器来验证JSON对象(它在中),该对象包含来自字段(在Python中是保留字)的。因此,我的模型应该如下所示: class Message(BaseModel): message_id: int from: Optional[str] date: int chat: Any ... 但是在此上下文中不允许使用from关键字 我怎么能这样做 注意:这与“为什么我们不能使用关键字作为属性”不同,因为这里我们得到了我们不控制的外部JSON,我们无论如何都应该使用f

我想通过使用验证器来验证JSON对象(它在中),该对象包含来自字段(在Python中是保留字)的。因此,我的模型应该如下所示:

class Message(BaseModel):
  message_id: int
  from: Optional[str]
  date: int
  chat: Any
  ...
但是在此上下文中不允许使用from关键字

我怎么能这样做

注意:这与“为什么我们不能使用关键字作为属性”不同,因为这里我们得到了我们不控制的外部JSON,我们无论如何都应该使用from字段来处理JSON。

I您可以将
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)

提议的副本的可能重复说明了为什么不能使用
from
作为属性,而不是如何在此处使用
from
作为键来容纳JSON对象。一种可能有效的方法(可能不是“正确”的方法)是自己更新注释:
消息。\uu注释\uu.update({'from':可选[str]}
并在验证后获取数据
valid\u data=Message(data).dict(by\u alias=True)