简体   繁体   中英

How validate few fields with Pydantic in huge nested json?

I have dict-like object, like:

    data = {
    # A lot of data here
    'json_data_feed':
        {'address':
             {'name': 'home_sweet_home'}
         }
    # A lot of data here
}

And i want to create Pydantic model with few fields. Im trying to do this:

class OfferById(pydantic.BaseModel):
    short_address: str = pydantic.Field(..., alias='name')

    @pydantic.validator('short_address', pre=True)
    def validate_short_address(cls, value):
        return value['json_data_feed']['address']

And it fails with exception:

    Some = OfferById(**data)
  File "pydantic/main.py", line 406, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for OfferById
name
  field required (type=value_error.missing)

Are there any solution here?

You can achieve this by means of root validator . For example:

class OfferById(BaseModel):
    short_address: str = Field(..., alias='name')

    @root_validator(pre=True)
    def validate_short_address(cls, values):
        values['name'] = values['json_data_feed']['address']['name']
        return values


print(OfferById(**data))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM