close

How to parse list of models with Pydantic

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to parse list of models with Pydantic in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How to parse list of models with Pydantic?

  1. How to parse list of models with Pydantic?

    The “right” way to do this in pydantic is to make use of “Custom Root Types”. You still need to make use of a container model:

  2. parse list of models with Pydantic

    The “right” way to do this in pydantic is to make use of “Custom Root Types”. You still need to make use of a container model:

Method 1

This is now possible using parse_obj_as.

from pydantic import parse_obj_as

users = [
    {"name": "user1", "age": 15}, 
    {"name": "user2", "age": 28}
]

m = parse_obj_as(List[User], users)

Method 2

To confirm and expand the previous answer, here is an “official” answer at pydantic-github – All credits to “dmontagu“:

The “right” way to do this in pydantic is to make use of “Custom Root Types”. You still need to make use of a container model:

class UserList(BaseModel):
    __root__: List[User]

but then the following will work:

UserList.parse_obj([
    {'id': '123', 'signup_ts': '2017-06-01 12:22', 'friends': [1, '2', b'3']},
    {'id': '456', 'signup_ts': '2017-06-02 12:22', 'friends': ['you']},
])

(and will put the values inside the root property).

Unfortunately, I think there is not good serialization support for this yet, so I think when you go to return the results, if you want to return just a list you’ll still need to return UserList.root.

I don’t think there is currently a unified interface that gets you a serialized/unstructured version of the model that respects the root_model, but if this is what you are looking for, it could be worth building.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read