Coverage for gws-app/gws/lib/jsonx/__init__.py: 36%
39 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-17 01:37 +0200
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-17 01:37 +0200
1import json
3import gws
6class Error(gws.Error):
7 pass
10def from_path(path: str):
11 """Converts a json file to a python dictionary.
13 Args:
14 path: Path to json file.
16 Returns:
17 A Python object.
19 Raises:
20 ``Exception``: If the given json is incorrect.
21 """
23 try:
24 with open(path, 'rb') as fp:
25 s = fp.read()
26 return json.loads(s.decode('utf8'))
27 except Exception as exc:
28 raise Error() from exc
31def from_string(s: str):
32 """Converts a json string to a python dictionary.
34 Args:
35 s: Json string.
37 Returns:
38 A Python object.
40 Raises:
41 ``Error``: If the given json is incorrect.
42 """
44 if not s.strip():
45 return {}
46 try:
47 return json.loads(s)
48 except Exception as exc:
49 raise Error() from exc
52def to_path(path: str, x, pretty: bool = False, ensure_ascii: bool = True, default=None):
53 """Converts a dictionary to a json file.
55 Args:
56 path: Destination of the json file.
57 x: The dict to convert.
58 pretty: If true then the json key-value pairs get ordered and correct indentation is used.
59 ensure_ascii: If true non ASCII characters will be escaped. Else those characters will not be escaped.
60 default: A function that should return a serializable version of obj or raise TypeError.
61 The default simply raises TypeError.
62 """
64 s = to_string(x, pretty=pretty, ensure_ascii=ensure_ascii, default=default)
65 try:
66 with open(path, 'wb') as fp:
67 fp.write(s.encode('utf8'))
68 except Exception as exc:
69 raise Error() from exc
72def to_string(x, pretty: bool = False, ensure_ascii: bool = True, default=None) -> str:
73 """Converts a dictionary to a json string.
75 Args:
76 x: The dict to convert.
77 pretty: If true then the json key-value pairs get ordered and correct indentation is used.
78 ensure_ascii: If true non ASCII characters will be escaped. Else those characters will not be escaped.
79 default: A function that should return a serializable version of obj or raise TypeError.
80 The default simply raises TypeError.
81 """
83 try:
84 if pretty:
85 return json.dumps(
86 x,
87 check_circular=False,
88 default=default or _json_default,
89 ensure_ascii=ensure_ascii,
90 indent=4,
91 sort_keys=True,
92 )
93 return json.dumps(
94 x,
95 check_circular=False,
96 default=default or _json_default,
97 ensure_ascii=ensure_ascii,
98 )
99 except Exception as exc:
100 raise Error() from exc
103def to_pretty_string(x, ensure_ascii: bool = True, default=None) -> str:
104 """Converts a dictionary to a pretty json string.
106 Args:
107 x: The dict to convert.
108 ensure_ascii: If true non ASCII characters will be escaped. Else those characters will not be escaped.
109 default: A function that should return a serializable version of obj or raise TypeError.
110 The default simply raises TypeError.
111 """
113 return to_string(x, pretty=True, ensure_ascii=ensure_ascii, default=default)
116def _json_default(x):
117 try:
118 return vars(x)
119 except TypeError:
120 return str(x)