Skip to content

Commit

Permalink
Allow bytes in from_json typing
Browse files Browse the repository at this point in the history
  • Loading branch information
davetapley committed Feb 11, 2024
1 parent b3fb6c5 commit e493deb
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions serde/json.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""
Serialize and Deserialize in JSON format.
"""
from typing import Any, overload, Optional
from typing import Any, AnyStr, overload, Optional, Union

from typing_extensions import Type

Expand All @@ -18,7 +18,7 @@ def json_dumps(obj: Any, **opts: Any) -> str:
opts["option"] = orjson.OPT_SERIALIZE_NUMPY
return orjson.dumps(obj, **opts).decode() # type: ignore

def json_loads(s: str, **opts: Any) -> Any:
def json_loads(s: Union[str, bytes], **opts: Any) -> Any:
return orjson.loads(s, **opts)

except ImportError:
Expand All @@ -32,7 +32,7 @@ def json_dumps(obj: Any, **opts: Any) -> str:
separators = opts.pop("separators", (",", ":"))
return json.dumps(obj, ensure_ascii=ensure_ascii, separators=separators, **opts)

def json_loads(s: str, **opts: Any) -> Any:
def json_loads(s: Union[str, bytes], **opts: Any) -> Any:
return json.loads(s, **opts)


Expand All @@ -45,9 +45,9 @@ def serialize(cls, obj: Any, **opts: Any) -> str:
return json_dumps(obj, **opts)


class JsonDeserializer(Deserializer[str]):
class JsonDeserializer(Deserializer[AnyStr]):
@classmethod
def deserialize(cls, data: str, **opts: Any) -> Any:
def deserialize(cls, data: AnyStr, **opts: Any) -> Any:
return json_loads(data, **opts)


Expand All @@ -71,17 +71,23 @@ def to_json(


@overload
def from_json(c: Type[T], s: str, de: Type[Deserializer[str]] = JsonDeserializer, **opts: Any) -> T:
def from_json(
c: Type[T], s: AnyStr, de: Type[Deserializer[AnyStr]] = JsonDeserializer, **opts: Any
) -> T:
...


# For Union, Optional etc.
@overload
def from_json(c: Any, s: str, de: Type[Deserializer[str]] = JsonDeserializer, **opts: Any) -> Any:
def from_json(
c: Any, s: AnyStr, de: Type[Deserializer[AnyStr]] = JsonDeserializer, **opts: Any
) -> Any:
...


def from_json(c: Any, s: str, de: Type[Deserializer[str]] = JsonDeserializer, **opts: Any) -> Any:
def from_json(
c: Any, s: AnyStr, de: Type[Deserializer[AnyStr]] = JsonDeserializer, **opts: Any
) -> Any:
"""
Deserialize from JSON into the object. [orjson](https://github.com/ijl/orjson) will be used
if installed.
Expand Down

0 comments on commit e493deb

Please sign in to comment.