-
Notifications
You must be signed in to change notification settings - Fork 244
Expand file tree
/
Copy pathjson.py
More file actions
30 lines (22 loc) · 817 Bytes
/
Copy pathjson.py
File metadata and controls
30 lines (22 loc) · 817 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import orjson
from pydantic.json import ENCODERS_BY_TYPE
from docarray.typing.abstract_type import AbstractType
def _default_orjson(obj):
"""
default option for orjson dumps.
:param obj:
:return: return a json compatible object
"""
if isinstance(obj, AbstractType):
return obj._docarray_to_json_compatible()
else:
for cls_, encoder in ENCODERS_BY_TYPE.items():
if isinstance(obj, cls_):
return encoder(obj)
return obj
def orjson_dumps(v, *, default=None) -> bytes:
# dumps to bytes using orjson
return orjson.dumps(v, default=_default_orjson, option=orjson.OPT_SERIALIZE_NUMPY)
def orjson_dumps_and_decode(v, *, default=None) -> str:
# dumps to bytes using orjson
return orjson_dumps(v, default=default).decode()