Use backslashreplace error strategy

This commit is contained in:
Rory Flynn 2023-11-15 11:33:18 +01:00
parent 6d0f819926
commit a8a35dab04
2 changed files with 3 additions and 7 deletions

View File

@ -30,12 +30,8 @@ class CustomJSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, bytes):
# If it's utf-8, try and use that first
try:
return o.decode("utf-8")
except UnicodeError:
# Otherwise use a hex representation for any byte type
return "0x" + o.hex()
# Decode as utf-8, replace any invalid UTF-8 bytes with escaped hex
return o.decode("utf-8", errors="backslashreplace")
# For all other types try to use the string representation.
return str(o)

View File

@ -85,7 +85,7 @@ class TestCustomJSONEncoder:
def test__bytes_non_utf_8(self):
assert (
json.dumps({"identifier": b"\xa8\xa9"}, cls=CustomJSONEncoder)
== '{"identifier": "0xa8a9"}'
== """{"identifier": "\\\\xa8\\\\xa9"}"""
)
def test__bytes_valid_utf_8(self):