-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #223 from parea-ai/PAI-408-fix-json-serializer-for…
…-trace-decorator feat: add universial json serializer
- Loading branch information
Showing
3 changed files
with
46 additions
and
13 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
from typing import Any | ||
|
||
import dataclasses | ||
import datetime | ||
import json | ||
|
||
import attrs | ||
|
||
|
||
def is_dataclass_instance(obj): | ||
return dataclasses.is_dataclass(obj) and not isinstance(obj, type) | ||
|
||
|
||
def is_attrs_instance(obj): | ||
return attrs.has(obj) | ||
|
||
|
||
class UniversalEncoder(json.JSONEncoder): | ||
def default(self, obj: Any): | ||
if isinstance(obj, str): | ||
return obj | ||
elif is_dataclass_instance(obj): | ||
return dataclasses.asdict(obj) | ||
elif is_attrs_instance(obj): | ||
return attrs.asdict(obj) | ||
elif isinstance(obj, (datetime.datetime, datetime.date, datetime.time)): | ||
return obj.isoformat() | ||
elif isinstance(obj, datetime.timedelta): | ||
return obj.total_seconds() | ||
else: | ||
return super().default(obj) | ||
|
||
|
||
def json_dumps(obj, **kwargs): | ||
return json.dumps(obj, cls=UniversalEncoder, **kwargs) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,7 +6,7 @@ build-backend = "poetry.core.masonry.api" | |
[tool.poetry] | ||
name = "parea-ai" | ||
packages = [{ include = "parea" }] | ||
version = "0.2.14" | ||
version = "0.2.15" | ||
description = "Parea python sdk" | ||
readme = "README.md" | ||
authors = ["joel-parea-ai <[email protected]>"] | ||
|