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 - using a list with json objects - Stack Overflow
JSONtoPydantic - Generate Pydantic Models from JSON in the browser
Generating json/dictionary from pydantic model
python - parse json file to Pydantic model - Stack Overflow
Videos
The following also works, and does not require a root type.
To convert from a List[dict] to a List[Item]:
items = parse_obj_as(List[Item], bigger_data)
To convert from JSON str to a List[Item]:
items = parse_raw_as(List[Item], bigger_data_json)
To convert from a List[Item] to a JSON str:
from pydantic.json import pydantic_encoder
bigger_data_json = json.dumps(items, default=pydantic_encoder)
or with a custom encoder:
from pydantic.json import pydantic_encoder
def custom_encoder(**kwargs):
def base_encoder(obj):
if isinstance(obj, BaseModel):
return obj.dict(**kwargs)
else:
return pydantic_encoder(obj)
return base_encoder
bigger_data_json = json.dumps(items, default=custom_encoder(by_alias=True))
To avoid having "each_item" in the ItemList, you can use the __root__ Pydantic keyword:
from typing import List
from pydantic import BaseModel
class Item(BaseModel):
thing_number: int
thing_description: str
thing_amount: float
class ItemList(BaseModel):
__root__: List[Item] # ⯇-- __root__
To build the item_list:
just_data = [
{"thing_number": 123, "thing_description": "duck", "thing_amount": 4.56},
{"thing_number": 456, "thing_description": "cow", "thing_amount": 7.89},
]
item_list = ItemList(__root__=just_data)
a_json_duck = {"thing_number": 123, "thing_description": "duck", "thing_amount": 4.56}
item_list.__root__.append(a_json_duck)
The web-frameworks supporting Pydantic often jsonify such ItemList as a JSON array without intermediate __root__ keyword.
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
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}?
» pip install json-schema-to-pydantic
» pip install json2python-models