Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate JSON field with name "from"

I want to validate JSON object (it is in Telegram Bot API) which contains from field (which is reserved word in Python) by using pydantic validator. So my model should look like the following:

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

But using from keyword is not allowed in this context.

How could I do this?

Note: this is different than "Why we can't use keywords as attributes" because here we get external JSON we don't control and we anyway should handle JSON with from field.

like image 888
likern Avatar asked Apr 10 '19 19:04

likern


2 Answers

I believe you can replace from with from_.

You can do it like this:

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

    class Config:
        fields = {
        'from_': 'from'
        }
    ...
like image 143
Amir Shabani Avatar answered Oct 11 '22 08:10

Amir Shabani


There might be a way to do this using a class statement, but I didn't see anything in a quick skim of the documentation. What you could do is use dynamic model creation instead.

fields = {
    'message_id': (int,),
    'from': (Optional[str], ...),
    'date': (int, ...),
    'chat': (Any, ...)
 }
 Message = create_model("Message", **fields)
like image 37
chepner Avatar answered Oct 11 '22 06:10

chepner