Skip to content

Commit

Permalink
Merge pull request #336 from emilhe/serialization2
Browse files Browse the repository at this point in the history
Serialization transform stability improvements
  • Loading branch information
emilhe authored Jun 28, 2024
2 parents 2307f59 + 2387379 commit 45a91c1
Showing 1 changed file with 14 additions and 2 deletions.
16 changes: 14 additions & 2 deletions dash_extensions/enrich.py
Original file line number Diff line number Diff line change
Expand Up @@ -1269,7 +1269,13 @@ class DataclassTransform(SerializationTransform):
def _try_load(self, data: Any, ann=None) -> Any:
if not dataclasses.is_dataclass(ann):
return data
return fromdict(ann, data)
if data is None:
return None
if isinstance(data, str):
data = json.loads(data)
if isinstance(data, dict):
return fromdict(ann, data)
raise ValueError(f"Unsupported data type for dataclass: {type(data)}")

def _try_dump(self, obj: Any) -> Any:
if not dataclasses.is_dataclass(obj):
Expand All @@ -1287,7 +1293,13 @@ class BaseModelTransform(SerializationTransform):
def _try_load(self, data: Any, ann=None) -> Any:
if not isinstance(ann, type(BaseModel)):
return data
return ann.model_validate_json(data)
if data is None:
return None
if isinstance(data, str):
return ann.model_validate_json(data)
if isinstance(data, dict):
return ann.model_validate(data)
raise ValueError(f"Unsupported data type for Pydantic model: {type(data)}")

def _try_dump(self, obj: Any) -> Any:
if not isinstance(obj, BaseModel):
Expand Down

0 comments on commit 45a91c1

Please sign in to comment.