I think I arrive a little bit late to the party, but I think this answer may come handy for future users having the same question.
To convert the dataclass to json you can use the combination that you are already using using (asdict plus json.dump).
from pydantic.dataclasses import dataclass
@dataclass
class User:
id: int
name: str
user = User(id=123, name="James")
d = asdict(user) # {'id': 123, 'name': 'James'
user_json = json.dumps(d)
print(user_json) # '{"id": 123, "name": "James"}'
# Or directly with pydantic_encoder
json.dumps(user, default=pydantic_encoder)
Then from the raw json you can use a BaseModel and the parse_raw method.
If you want to deserialize json into pydantic instances, I recommend you using the parse_raw method:
user = User.__pydantic_model__.parse_raw('{"id": 123, "name": "James"}')
print(user)
# id=123 name='James'
Otherwise, if you want to keep the dataclass:
json_raw = '{"id": 123, "name": "James"}'
user_dict = json.loads(json_raw)
user = User(**user_dict)
Answer from Guillem on Stack OverflowI think I arrive a little bit late to the party, but I think this answer may come handy for future users having the same question.
To convert the dataclass to json you can use the combination that you are already using using (asdict plus json.dump).
from pydantic.dataclasses import dataclass
@dataclass
class User:
id: int
name: str
user = User(id=123, name="James")
d = asdict(user) # {'id': 123, 'name': 'James'
user_json = json.dumps(d)
print(user_json) # '{"id": 123, "name": "James"}'
# Or directly with pydantic_encoder
json.dumps(user, default=pydantic_encoder)
Then from the raw json you can use a BaseModel and the parse_raw method.
If you want to deserialize json into pydantic instances, I recommend you using the parse_raw method:
user = User.__pydantic_model__.parse_raw('{"id": 123, "name": "James"}')
print(user)
# id=123 name='James'
Otherwise, if you want to keep the dataclass:
json_raw = '{"id": 123, "name": "James"}'
user_dict = json.loads(json_raw)
user = User(**user_dict)
Pydantic recommends using parse_raw to deserialize JSON strings.
Class definition
from pydantic import BaseModel
class ResponseData(BaseModel):
status_code: int
text: str
reason: str
class Config:
orm_mode = True
JSON to BaseModel conversion
x = ResponseData(status_code=200, text="", reason="")
json = x.json()
response = ResponseData.parse_raw(json)
assert x == response
print(response.dict())
python - pydantic convert to jsonable dict (not full json string) - Stack Overflow
How to json serialize list of BaseModels
Generating json/dictionary from pydantic model
Using Pydantic structured outputs in batch mode
Videos
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'}
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.
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}?
https://jsontopydantic.com
Hi there! I built this over the weekend and figured someone other than myself might find it useful.
Like many who work with REST APIs in Python, I've recently fallen in love with Pydantic. If you haven't heard of Pydantic, it's a data validation and parsing library that makes working with JSON in Python quite pleasant.
I needed a quick way to generate a Pydantic model from any given sample of JSON, and hacked together this application to do so. You can paste in a valid JSON string, and you'll get a valid Pydantic model back.
This is helpful if you're working with poorly documented APIs, really big objects, or have lots of edge cases to catch.
Check it out and let me know what you think!
Code -> https://github.com/brokenloop/jsontopydantic
Simple and updated answer Pydantic +2
Using RootModel
from datetime import date, datetime
from pydantic import BaseModel, RootModel
class Car(BaseModel):
model: str
is_fast: bool
buy_date: date
buy_datetime: datetime
max_speed: float
Cars = RootModel[list[Car]]
cars = Cars(
[
Car(
model=f"G Wagon {i}",
is_fast=i % 2 == 0,
buy_date=datetime.now().date(),
buy_datetime=datetime.now(),
max_speed=i + 1337,
)
for i in range(2)
]
)
json_txt = cars.model_dump_json(indent=2)
print(json_txt)
[
{
"model": "G Wagon 0",
"is_fast": true,
"buy_date": "2025-01-27",
"buy_datetime": "2025-01-27T14:41:04.559555",
"max_speed": 1337.0
},
{
"model": "G Wagon 1",
"is_fast": false,
"buy_date": "2025-01-27",
"buy_datetime": "2025-01-27T14:41:04.560554",
"max_speed": 1338.0
}
]
https://docs.pydantic.dev/latest/concepts/models/#rootmodel-and-custom-root-types
I would like to know the answer too. But it didn't come, so I did my own experiments. Hope it helps.
Q1: Does dump_json() skips validation?
A1: It looks like it just serializes. To get a correct output I had to use the TypeAdapter twice: first time to valdiate, then to serialize.
Q2: Problem with exclude=
A2: Please read the Advanced include and exclude
Below is my little test program with mocked data:
from pydantic import BaseModel, TypeAdapter
class UserPydanticModel(BaseModel):
name: str
passwd: str
demo: bool = True
users_from_db = [dict(name=f'usr{i}', passwd=f'pwd{i}') for i in range(3)]
ta = TypeAdapter(list[UserPydanticModel])
users = ta.validate_python(users_from_db)
dumped = ta.dump_json(users, exclude={'__all__': 'passwd'})
print(dumped)
# b'[{"name":"usr0","demo":true},{"name":"usr1","demo":true},{"name":"usr2","demo":true}]'
» pip install json-schema-to-pydantic