Coverage for gws-app/gws/lib/jsonx/__init__.py: 71%
38 statements
« prev ^ index » next coverage.py v7.11.0, created at 2025-10-16 23:09 +0200
« prev ^ index » next coverage.py v7.11.0, created at 2025-10-16 23:09 +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 gws.u.write_file_b(path, s.encode('utf8'))
67 except Exception as exc:
68 raise Error() from exc
71def to_string(x, pretty: bool = False, ensure_ascii: bool = True, default=None) -> str:
72 """Converts a dictionary to a json string.
74 Args:
75 x: The dict to convert.
76 pretty: If true then the json key-value pairs get ordered and correct indentation is used.
77 ensure_ascii: If true non ASCII characters will be escaped. Else those characters will not be escaped.
78 default: A function that should return a serializable version of obj or raise TypeError.
79 The default simply raises TypeError.
80 """
82 try:
83 if pretty:
84 return json.dumps(
85 x,
86 check_circular=False,
87 default=default or _json_default,
88 ensure_ascii=ensure_ascii,
89 indent=4,
90 sort_keys=True,
91 )
92 return json.dumps(
93 x,
94 check_circular=False,
95 default=default or _json_default,
96 ensure_ascii=ensure_ascii,
97 )
98 except Exception as exc:
99 raise Error() from exc
102def to_pretty_string(x, ensure_ascii: bool = True, default=None) -> str:
103 """Converts a dictionary to a pretty json string.
105 Args:
106 x: The dict to convert.
107 ensure_ascii: If true non ASCII characters will be escaped. Else those characters will not be escaped.
108 default: A function that should return a serializable version of obj or raise TypeError.
109 The default simply raises TypeError.
110 """
112 return to_string(x, pretty=True, ensure_ascii=ensure_ascii, default=default)
115def _json_default(x):
116 try:
117 return vars(x)
118 except TypeError:
119 return str(x)