python - Initializing a pydantic dataclass from json - Stack Overflow
Generating json/dictionary from pydantic model
Allow partial needs `'trailing-strings'` mode, same as `pydantic_core.from_json`
JSONtoPydantic - Generate Pydantic Models from JSON in the browser
Videos
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)
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())
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