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.
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)
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"}}
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.