Edit on GitHub

serde.json

Serialize and Deserialize in JSON format.

  1"""
  2Serialize and Deserialize in JSON format.
  3"""
  4
  5from typing import Any, AnyStr, overload, Optional, Union
  6
  7from .compat import T
  8from .de import Deserializer, from_dict
  9from .se import Serializer, to_dict
 10
 11# Lazy numpy imports to improve startup time
 12
 13try:  # pragma: no cover
 14    import orjson
 15
 16    def json_dumps(obj: Any, **opts: Any) -> str:
 17        if "option" not in opts:
 18            opts["option"] = orjson.OPT_SERIALIZE_NUMPY
 19        return orjson.dumps(obj, **opts).decode()  # type: ignore
 20
 21    def json_loads(s: Union[str, bytes], **opts: Any) -> Any:
 22        return orjson.loads(s, **opts)
 23
 24except ImportError:
 25    import json
 26
 27    def json_dumps(obj: Any, **opts: Any) -> str:
 28        if "default" not in opts:
 29            from .numpy import encode_numpy
 30
 31            opts["default"] = encode_numpy
 32        # compact output
 33        ensure_ascii = opts.pop("ensure_ascii", False)
 34        separators = opts.pop("separators", (",", ":"))
 35        return json.dumps(obj, ensure_ascii=ensure_ascii, separators=separators, **opts)
 36
 37    def json_loads(s: Union[str, bytes], **opts: Any) -> Any:
 38        return json.loads(s, **opts)
 39
 40
 41__all__ = ["from_json", "to_json"]
 42
 43
 44class JsonSerializer(Serializer[str]):
 45    @classmethod
 46    def serialize(cls, obj: Any, **opts: Any) -> str:
 47        return json_dumps(obj, **opts)
 48
 49
 50class JsonDeserializer(Deserializer[AnyStr]):
 51    @classmethod
 52    def deserialize(cls, data: AnyStr, **opts: Any) -> Any:
 53        return json_loads(data, **opts)
 54
 55
 56def to_json(
 57    obj: Any,
 58    cls: Optional[Any] = None,
 59    se: type[Serializer[str]] = JsonSerializer,
 60    reuse_instances: bool = False,
 61    convert_sets: bool = True,
 62    skip_none: bool = False,
 63    **opts: Any,
 64) -> str:
 65    """
 66    Serialize the object into JSON str. [orjson](https://github.com/ijl/orjson)
 67    will be used if installed.
 68
 69    You can pass any serializable `obj`. If you supply other keyword arguments,
 70    they will be passed in `dumps` function.
 71    By default, numpy objects are serialized, this behaviour can be customized with the `option`
 72    argument with [orjson](https://github.com/ijl/orjson#numpy), or the `default` argument with
 73    Python standard json library.
 74
 75    * `skip_none`: When set to True, any field in the class with a None value is excluded from the
 76    serialized output. Defaults to False.
 77
 78    If you want to use another json package, you can subclass `JsonSerializer` and implement
 79    your own logic.
 80    """
 81    return se.serialize(
 82        to_dict(
 83            obj,
 84            c=cls,
 85            reuse_instances=reuse_instances,
 86            convert_sets=convert_sets,
 87            skip_none=skip_none,
 88        ),
 89        **opts,
 90    )
 91
 92
 93@overload
 94def from_json(
 95    c: type[T], s: AnyStr, de: type[Deserializer[AnyStr]] = JsonDeserializer, **opts: Any
 96) -> T: ...
 97
 98
 99# For Union, Optional etc.
100@overload
101def from_json(
102    c: Any, s: AnyStr, de: type[Deserializer[AnyStr]] = JsonDeserializer, **opts: Any
103) -> Any: ...
104
105
106def from_json(
107    c: Any, s: AnyStr, de: type[Deserializer[AnyStr]] = JsonDeserializer, **opts: Any
108) -> Any:
109    """
110    Deserialize from JSON into the object. [orjson](https://github.com/ijl/orjson) will be used
111    if installed.
112
113    `c` is a class object and `s` is JSON bytes or str. If you supply other keyword arguments,
114    they will be passed in `loads` function.
115
116    If you want to use another json package, you can subclass `JsonDeserializer` and implement
117    your own logic.
118    """
119    return from_dict(c, de.deserialize(s, **opts), reuse_instances=False)
def from_json( c: Any, s: ~AnyStr, de: type[serde.de.Deserializer[~AnyStr]] = <class 'serde.json.JsonDeserializer'>, **opts: Any) -> Any:
107def from_json(
108    c: Any, s: AnyStr, de: type[Deserializer[AnyStr]] = JsonDeserializer, **opts: Any
109) -> Any:
110    """
111    Deserialize from JSON into the object. [orjson](https://github.com/ijl/orjson) will be used
112    if installed.
113
114    `c` is a class object and `s` is JSON bytes or str. If you supply other keyword arguments,
115    they will be passed in `loads` function.
116
117    If you want to use another json package, you can subclass `JsonDeserializer` and implement
118    your own logic.
119    """
120    return from_dict(c, de.deserialize(s, **opts), reuse_instances=False)

Deserialize from JSON into the object. orjson will be used if installed.

c is a class object and s is JSON bytes or str. If you supply other keyword arguments, they will be passed in loads function.

If you want to use another json package, you can subclass JsonDeserializer and implement your own logic.

def to_json( obj: Any, cls: Optional[Any] = None, se: type[serde.se.Serializer[str]] = <class 'serde.json.JsonSerializer'>, reuse_instances: bool = False, convert_sets: bool = True, skip_none: bool = False, **opts: Any) -> str:
57def to_json(
58    obj: Any,
59    cls: Optional[Any] = None,
60    se: type[Serializer[str]] = JsonSerializer,
61    reuse_instances: bool = False,
62    convert_sets: bool = True,
63    skip_none: bool = False,
64    **opts: Any,
65) -> str:
66    """
67    Serialize the object into JSON str. [orjson](https://github.com/ijl/orjson)
68    will be used if installed.
69
70    You can pass any serializable `obj`. If you supply other keyword arguments,
71    they will be passed in `dumps` function.
72    By default, numpy objects are serialized, this behaviour can be customized with the `option`
73    argument with [orjson](https://github.com/ijl/orjson#numpy), or the `default` argument with
74    Python standard json library.
75
76    * `skip_none`: When set to True, any field in the class with a None value is excluded from the
77    serialized output. Defaults to False.
78
79    If you want to use another json package, you can subclass `JsonSerializer` and implement
80    your own logic.
81    """
82    return se.serialize(
83        to_dict(
84            obj,
85            c=cls,
86            reuse_instances=reuse_instances,
87            convert_sets=convert_sets,
88            skip_none=skip_none,
89        ),
90        **opts,
91    )

Serialize the object into JSON str. orjson will be used if installed.

You can pass any serializable obj. If you supply other keyword arguments, they will be passed in dumps function. By default, numpy objects are serialized, this behaviour can be customized with the option argument with orjson, or the default argument with Python standard json library.

  • skip_none: When set to True, any field in the class with a None value is excluded from the serialized output. Defaults to False.

If you want to use another json package, you can subclass JsonSerializer and implement your own logic.