How to read and write a Pydantic class to/from a JSON file.

How to read and write a Pydantic class to/from a JSON file.

Pydantic classes are (de)serializable, although deserializing can be a little tricky.

Here is some example code, with functions to load and save data for an example Pydantic class 'MySerializableType':

import logging
from cornsnake import util_file, util_json
from pydantic import BaseModel, TypeAdapter

logger = logging.getLogger(__file__)

class CustomBaseModel(BaseModel):
    class Config:
        populate_by_name = True
        extra = "forbid"

class MySerializableType(CustomBaseModel):
    favourite_color: str = "blue"
    file_schema_version: str = "0.2"

def read_from_file(path_to_file: str) -> MySerializableType:
    try:
        json_data = util_json.read_from_json_file(path_to_file)
        deserialized =  TypeAdapter(MySerializableType).validate_python(json_data)
        return deserialized
    except Exception as e:
        logger.exception(e)


def save_to_file(path_to_file: str, data: MySerializableType) -> None:
    json_data = data.model_dump_json(by_alias=True)
    util_file.write_text_to_file(json_data, path_to_file)


notes:
- read_from_file(): TypeAdapter is used to validate and map the JSON back to the expected Pydantic class
- save_to_file(): model_dump_json() is used to serialize the Pydantic object to JSON. The parameter by_alias=True ensures that the BaseModel config options are followed (in particular, if camelCasing is specified as opposed to snake_case).

Comments