'How to map values from nested dictionary and list using Pydantic library?
I am trying to map values from a nested dict to Pydantic model. It doesnt work, because dict has a nested structure.
Now I have such format of the response:
{
"data": {
"3": { <---- its id
"type": "Polygon", <---- its coords
"coordinates": []},
"4": {
"type": "Polygon",
"coordinates": []}}}
I am trying to do response with such structure:
{"data":
{
"1": [{
"_id": 3,
"coords": {
"type": "Polygon",
"coordinates": []}}],
"2": [{
"id": 4,
"coords": {
"type": "Polygon",
"coordinates": []}]
},....}
Keys "1", "2" and so on are generating in the loop using func enumerate()
I have a Pydantic model with attributes:
class Serializer(BaseModel):
id: Optional[int] = None
coords: Optional[dict] = None
But have validation Error
pydantic.error_wrappers.ValidationError: 2 validation errors
response -> cluster_id
field required (type=value_error.missing)
response -> coords_cluster
field required (type=value_error.missing)
How can I map the value from dict using Pydantic model?
Is there an easy way instead of using a root_validator to parse the given structure to my flat pydantic Model?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
