Debian Codegraph @

DisplayCAL/demjson_compat.py

raw
1 """demjson 1.3 compatibility module."""
2
3 from __future__ import annotations
4
5 import json
6 import sys
7 from io import StringIO
8 from typing import Any
9
10 DEBUG = False
11
12
13 def debug_print(*args: list, **kwargs: dict) -> None:
14 """Print debug information if DEBUG is enabled."""
15 if DEBUG:
16 sys.stdout.write(*args, **kwargs)
17
18
19 def decode(txt: str, strict: bool = False, encoding: None | str = None, **kw) -> Any: # noqa: ANN401
20 """Decode a JSON-encoded string into a Python object.
21
22 If 'strict' is set to True, then only strictly-conforming JSON
23 output will be produced. Note that this means that some types
24 of values may not be convertible and will result in a
25 JSONEncodeError exception.
26
27 The input string can be either a python string or a python unicode
28 string. If it is already a unicode string, then it is assumed
29 that no character set decoding is required.
30
31 However, if you pass in a non-Unicode text string (i.e., a python
32 type 'str') then an attempt will be made to auto-detect and decode
33 the character encoding. This will be successful if the input was
34 encoded in any of UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE),
35 and of course plain ASCII works too.
36
37 Note though that if you know the character encoding, then you
38 should convert to a unicode string yourself, or pass it the name
39 of the 'encoding' to avoid the guessing made by the auto
40 detection, as with
41
42 python_object = demjson.decode( input_bytes, encoding='utf8' )
43
44 Optional keywords arguments are ignored.
45
46 Args:
47 txt (str): The JSON-encoded string to decode.
48 strict (bool): If True, only strictly conforming JSON is accepted.
49 encoding (str, optional): The character encoding of the input string.
50 Defaults to None.
51 **kw: Additional keyword arguments (ignored).
52
53 Returns:
54 Any: The decoded Python object.
55 """
56 if strict:
57 return json.loads(txt, strict=strict)
58
59 dem_json_preprocessor = DEMJSONPreprocessor()
60 txt = dem_json_preprocessor.process(txt)
61
62 return json.loads(txt)
63
64
65 class DEMJSONPreprocessor:
66 """A JSON preprocessor that is compatible with demjson 1.3."""
67
68 def __init__(self) -> None:
69 self.prev = None
70 self.escape = False
71 self.expect_comment = False
72 self.in_comment = False
73 self.comment_multiline = False
74 self.in_quote = False
75 self.write = True
76
77 def process(self, txt: str) -> Any: # noqa: ANN401
78 """Process the input JSON string to remove comments.
79
80 Args:
81 txt (str): The JSON string to process.
82
83 Returns:
84 str: The processed JSON string with comments removed.
85 """
86 # Remove comments
87 io = StringIO()
88 for c in txt:
89 debug_print(c)
90 self.write = True
91 self.process_character(c)
92 if self.write and not self.expect_comment and not self.in_comment:
93 io.write(c)
94 self.prev = c
95 txt = io.getvalue()
96 debug_print("\n")
97 if DEBUG:
98 print("JSON:", txt)
99
100 return txt
101
102 def process_character(self, c: str) -> None:
103 """Process a character in the JSON string for comment handling.
104
105 Args:
106 c (str): The current character being processed.
107 """
108 if c == "\\":
109 debug_print("<ESCAPE>")
110 self.escape = True
111 elif self.escape:
112 debug_print("</ESCAPE>")
113 self.escape = False
114 else:
115 if not self.in_quote:
116 if c == "/":
117 self.handle_forward_slash_char()
118 elif c == "*":
119 self.handle_multiline_comment()
120 elif self.expect_comment:
121 debug_print("</EXPECT_COMMENT>")
122 self.expect_comment = False
123 if c == "\n":
124 self.handle_newline_char()
125 elif c == '"' and not self.in_comment:
126 self.handle_quote_status()
127
128 def handle_forward_slash_char(self) -> None:
129 """Handle the forward slash character in comment processing."""
130 if self.expect_comment:
131 debug_print("<COMMENT>")
132 self.in_comment = True
133 self.comment_multiline = False
134 self.expect_comment = False
135 elif self.in_comment and self.prev == "*":
136 debug_print("</MULTILINECOMMENT>")
137 self.in_comment = False
138 self.comment_multiline = False
139 self.write = False
140 elif not self.in_comment:
141 debug_print("<EXPECT_COMMENT>")
142 self.expect_comment = True
143
144 def handle_multiline_comment(self) -> None:
145 """Handle the start of a multiline comment."""
146 if self.expect_comment:
147 debug_print("<MULTILINECOMMENT>")
148 self.in_comment = True
149 self.comment_multiline = True
150 self.expect_comment = False
151
152 def handle_newline_char(self) -> None:
153 """Handle newline character in comment processing."""
154 if self.in_comment and not self.comment_multiline:
155 debug_print("</COMMENT>")
156 self.in_comment = False
157 self.write = False
158
159 def handle_quote_status(self) -> None:
160 """Toggle the in_quote status and print debug information."""
161 if self.in_quote:
162 debug_print("</QUOTE>")
163 self.in_quote = False
164 else:
165 debug_print("<QUOTE>")
166 self.in_quote = True
167
168
169 def encode(
170 obj: Any, # noqa: ANN401
171 strict: bool = False,
172 compactly: bool = True,
173 escape_unicode: bool = False,
174 encoding: None | str = None,
175 ) -> str:
176 """Encode a Python object into a JSON-encoded string.
177
178 'strict' is ignored.
179
180 If 'compactly' is set to True, then the resulting string will
181 have all extraneous white space removed; if False then the
182 string will be "pretty printed" with whitespace and indentation
183 added to make it more readable.
184
185 If 'escape_unicode' is set to True, then all non-ASCII characters
186 will be represented as a unicode escape sequence; if False then
187 the actual real unicode character will be inserted.
188
189 If no encoding is specified (encoding=None) then the output will
190 either be a Python string (if entirely ASCII) or a Python unicode
191 string type.
192
193 However if an encoding name is given then the returned value will
194 be a python string which is the byte sequence encoding the JSON
195 value. As the default/recommended encoding for JSON is UTF-8,
196 you should almost always pass in encoding='utf8'.
197
198 Args:
199 obj (Any): The Python object to encode.
200 strict (bool): Ignored, for compatibility.
201 compactly (bool): If True, the output will be compact; if False, it
202 will be pretty-printed with indentation.
203 escape_unicode (bool): If True, non-ASCII characters will be escaped;
204 if False, they will be included as actual characters.
205 encoding (str, optional): The character encoding for the output string.
206 Defaults to None.
207
208 Returns:
209 str: The JSON-encoded string.
210 """
211 if compactly:
212 indent = None
213 separators = (",", ":")
214 else:
215 indent = 2
216 separators = (",", ": ")
217
218 ensure_ascii = escape_unicode or encoding is not None
219
220 return json.dumps(
221 obj,
222 ensure_ascii=ensure_ascii,
223 indent=indent,
224 separators=separators,
225 )