How to map values from nested dict to Pydantic Model?

Viewed 4662

I am trying to map a value from a nested dict/json to my Pydantic model. For me, this works well when my json/dict has a flat structure. However, I am struggling to map values from a nested structure to my Pydantic Model.

Lets assume I have a json/dict in the following format:

d = {
"p_id": 1,
"billing": {
    "first_name": "test"
}

In addition, I have a Pydantic model with two attributes:

class Order(BaseModel):
    p_id: int
    pre_name: str

How can I map the value from the key first_nameto my Pydantic attribute pre_name?

Is there an easy way instead of using a root_validator to parse the given structure to my flat pydantic Model?

1 Answers

You can customize __init__ of your model class:

from pydantic import BaseModel

d = {
    "p_id": 1,
    "billing": {
        "first_name": "test"
    }
}


class Order(BaseModel):
    p_id: int
    pre_name: str

    def __init__(self, **kwargs):
        kwargs["pre_name"] = kwargs["billing"]["first_name"]
        super().__init__(**kwargs)


print(Order.parse_obj(d))  # p_id=1 pre_name='test'
Related