Skip to content

Commit 61a52e3

Browse files
committed
JSON output: handle bytes, and disregard JSON encoding failures
Quite unexpectedly, there is a kind of report, that has content in bytes: ExtractCommandFailedReport, as the stdout/stderr streams are in bytes. It has made the metadata reporting fail in one case, so the custom JSON encoding has been changed to make sensible output when running into an unknown object, but never fail.
1 parent df9aea8 commit 61a52e3

File tree

1 file changed

+15
-4
lines changed

1 file changed

+15
-4
lines changed

unblob/models.py

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -136,18 +136,29 @@ def to_json(self, indent=" "):
136136

137137
class _JSONEncoder(json.JSONEncoder):
138138
def default(self, obj):
139-
if isinstance(obj, Enum):
140-
return obj.name
141-
142139
if attr.has(type(obj)):
143140
extend_attr_output = True
144141
attr_output = attr.asdict(obj, recurse=not extend_attr_output)
145142
attr_output["__typename__"] = obj.__class__.__name__
146143
return attr_output
147144

145+
if isinstance(obj, Enum):
146+
return obj.name
147+
148148
if isinstance(obj, Path):
149149
return str(obj)
150-
return json.JSONEncoder.default(self, obj)
150+
151+
if isinstance(obj, bytes):
152+
try:
153+
return obj.decode()
154+
except UnicodeDecodeError:
155+
return str(obj)
156+
157+
logger.error(f"JSONEncoder met a non-JSON encodable value: {obj}")
158+
# the usual fail path of custom JSONEncoders is to call the parent and let it fail
159+
# return json.JSONEncoder.default(self, obj)
160+
# instead of failing, just return something usable
161+
return f"Non-JSON encodable value: {obj}"
151162

152163

153164
class ExtractError(Exception):

0 commit comments

Comments
 (0)