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