How do I convert this data structure to JSON using Pydantic?

Viewed 1186

I have a data structure which consists of a dictionary with string keys, and the value for each key is a Pydantic model.

For example, the dictionary might look like this:

{
 "hello": MyPydanticModel(name="hello"),
 "there": MyPydanticModel(name="there")
}

I'm aware that I can call .json() to convert the Pydantic models into JSON, but what would be the most straightforward way to convert the dictionary to JSON. Would I need to use py2json or some other library?

Many thanks in advance.

2 Answers

You also can create model for the data structure with mapping root type and use its json method. Like so:

from typing import Dict
from pydantic import BaseModel


class MyPydanticModel(BaseModel):
    name: str


class MyPydanticModelOut(BaseModel):
    __root__: Dict[str, MyPydanticModel]


obj = {
    'hello': MyPydanticModel(name='a'),
    'there': MyPydanticModel(name='b')
}

print(MyPydanticModelOut.parse_obj(obj).json())  # {"hello": {"name": "a"}, "there": {"name": "b"}}
import json
from pydantic import BaseModel

class Example(BaseModel):
    id: int

table = {
    'a': Example(id=1),
    'b': Example(id=2)
}

_dict = {k: v.dict() for k, v in table.items()}
_json = json.dumps(_dict)

Related