Initializing a pydantic dataclass from json

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)