-
Notifications
You must be signed in to change notification settings - Fork 13
/
json.py
47 lines (38 loc) · 1.23 KB
/
json.py
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
from __future__ import annotations
import json
from typing import Any, Type
from ufoLib2.converters import structure, unstructure
from ufoLib2.typing import T
have_orjson = False
try:
import orjson
have_orjson = True
except ImportError:
pass
def dumps(
obj: Any,
indent: int | None = None,
sort_keys: bool = False,
**kwargs: Any,
) -> bytes:
data = unstructure(obj)
if have_orjson:
if indent is not None:
if indent != 2:
raise ValueError("indent must be 2 or None for orjson")
kwargs["option"] = kwargs.pop("option", 0) | orjson.OPT_INDENT_2
if sort_keys:
kwargs["option"] = kwargs.pop("option", 0) | orjson.OPT_SORT_KEYS
# orjson.dumps always returns bytes
result = orjson.dumps(data, **kwargs)
else:
# built-in json.dumps returns a string, not bytes, hence the encoding
s = json.dumps(data, indent=indent, sort_keys=sort_keys, **kwargs)
result = s.encode("utf-8")
return result
def loads(s: str | bytes, object_class: Type[T], **kwargs: Any) -> T:
if have_orjson:
data = orjson.loads(s, **kwargs)
else:
data = json.loads(s, **kwargs)
return structure(data, object_class)