Debian Codegraph @

third_party/python/taskcluster_taskgraph/taskgraph/util/json.py

raw
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
4
5 """
6 This module is a compatibility shim between stdlib json and orjson.
7 It uses orjson if available, and falls back to stdlib json.
8
9 It only supports features and parameters that both modules support,
10 and attempts to produce identical output regardless of which module
11 is used.
12
13 The interface is a subset of what's supported by stdlib json.
14 """
15
16 from __future__ import annotations
17
18 import json
19 from typing import TYPE_CHECKING, Any, Callable
20
21 if TYPE_CHECKING:
22 from _typeshed import SupportsRead, SupportsWrite
23
24 try:
25 import orjson
26 except ImportError:
27 orjson = None
28
29
30 def loads(s: str | bytes | bytearray) -> Any:
31 if orjson:
32 return orjson.loads(s)
33
34 return json.loads(s)
35
36
37 def load(fh: SupportsRead[str | bytes]) -> Any:
38 if orjson:
39 return loads(fh.read())
40 return json.load(fh)
41
42
43 def dumps(
44 obj: Any,
45 default: Callable[[Any], Any] | None = None,
46 indent: int | None = None,
47 sort_keys: bool = False,
48 ) -> str:
49 if indent and indent != 2:
50 raise ValueError("An indent other than 2 is not supported!")
51
52 if orjson:
53 option = 0
54 if indent:
55 option |= orjson.OPT_INDENT_2
56
57 if sort_keys:
58 option |= orjson.OPT_SORT_KEYS
59
60 return orjson.dumps(obj, default=default, option=option).decode("utf-8")
61
62 separators = (",", ": ") if indent else (",", ":")
63 return json.dumps(
64 obj,
65 default=default,
66 indent=indent,
67 sort_keys=sort_keys,
68 separators=separators,
69 )
70
71
72 def dump(obj: Any, fh: SupportsWrite[str], **kwargs) -> None:
73 fh.write(dumps(obj, **kwargs))