Pydantic 1.x (old answer)
The current version of pydantic does not support creating jsonable dict straightforwardly. But you can use the following trick:
Note: This is a suboptimal solution
class Model(BaseModel):
the_id: UUID = Field(default_factory=uuid4)
print(json.loads(Model().json()))
{'the_id': '4c94e7bc-78fe-48ea-8c3b-83c180437774'}
Or more efficiently by means of orjson
orjson.loads(Model().json())
Pydantic 2
There is the model_dump() method accepting the mode parameter.
mode: Literal['json', 'python'] | str = 'python'
If mode is 'json', the dictionary will only contain JSON serializable types.
If mode is 'python', the dictionary may contain any Python objects.
class Model(BaseModel):
the_id: UUID = Field(default_factory=uuid4)
print(Model().model_dump(mode='json'))
# {'the_id': '4c94e7bc-78fe-48ea-8c3b-83c180437774'}
Answer from alex_noname on Stack OverflowPydantic 1.x (old answer)
The current version of pydantic does not support creating jsonable dict straightforwardly. But you can use the following trick:
Note: This is a suboptimal solution
class Model(BaseModel):
the_id: UUID = Field(default_factory=uuid4)
print(json.loads(Model().json()))
{'the_id': '4c94e7bc-78fe-48ea-8c3b-83c180437774'}
Or more efficiently by means of orjson
orjson.loads(Model().json())
Pydantic 2
There is the model_dump() method accepting the mode parameter.
mode: Literal['json', 'python'] | str = 'python'
If mode is 'json', the dictionary will only contain JSON serializable types.
If mode is 'python', the dictionary may contain any Python objects.
class Model(BaseModel):
the_id: UUID = Field(default_factory=uuid4)
print(Model().model_dump(mode='json'))
# {'the_id': '4c94e7bc-78fe-48ea-8c3b-83c180437774'}
The official method in Pydantic 2 is using the .model_dump() method with mode="json" argument:
print(instance.model_dump(mode="json"))
From the Pydantic 2 documentation:
mode: The mode in whichto_pythonshould run. If mode is'json', the output will only contain JSON serializable types. If mode is'python', the output may contain non-JSON-serializable Python objects.
Generating json/dictionary from pydantic model
Model - coerce string to dict for field
python - How to write a Pydantic model to accept a Dictionary of Dictionaries - Stack Overflow
python - Generate pydantic model from a dict - Stack Overflow
Videos
I'm curious about functionality of pydantic. Let's say I have the following class:
from pydantic import BaseModel, Field
class SampleModel(BaseModel):
positive: int = Field(gt=0, examples=[6])
non_negative: int = Field(ge=0, examples=[5])
Is there a way to generate a .json or dict object that looks like: {'positive': 6, 'non_negative':5}?
If all you're trying to do is have a dictionary of BarModel's in another model, this answers your question:
from typing import Dict
from pydantic import BaseModel
class BarModel(BaseModel):
whatever: float
foo: str
class FooBarModel(BaseModel):
dictionaries: Dict[str, BarModel]
m1 = FooBarModel(dictionaries={
'a': {'whatever': 12.3, 'foo': 'hello'},
'b': {'whatever': 12.4, 'foo': 'bye'}
}
print(m1.dict())
You already found your magic combination, you haven't realized it yet.
from pydantic import BaseModel
from typing import Dict
class BarModel(BaseModel):
whatever: float
foo: str
class FooBarModel(BaseModel):
banana: str
bar: Dict[str, BarModel]
m1 = FooBarModel(banana="a", bar={
'a':{'whatever': 12.3, 'foo':'hello'},
'b':{'whatever': 12.4, 'foo':'bye'}
})
assert m1.dict() == {'banana': 'a', 'bar': {'a': {'whatever': 12.3, 'foo': 'hello'}, 'b': {'whatever': 12.4, 'foo': 'bye'}}}
This runs without any errors.
Note that we still have banana, if you want to discard it, simply delete.
If you wanted use pure typing and some static analyzer your examples would evaluate to this
from typing import Dict, Union
m = FooBarModel(banana='a', bar={'whatever': 12.3, 'foo':'hello'})
m: Dict[str, Union[str, Dict[str, Union[float, str]]]]
But what you want is actually this
from typing import Dict, Union
m1 = FooBarModel({
'a':{'whatever': 12.3, 'foo':'hello'},
'b':{'whatever': 12.4, 'foo':'bye'}
})
m1: Dict[str, Union[str, Dict[str, Dict[str, Union[float, str]]]]]
In Pydantic 2, you can use MyModel.model_validate(my_dict) to generate a model from a dictionary. According to the documentation –
this is very similar to the
__init__method of the model, except it takes a dict rather than keyword arguments.
If you're Pydantic 1, the method is parse_obj instead.
You can also use its __init__ method:
your_model = YourModel(**your_dict)