Skip to content

Commit

Permalink
bugfix
Browse files Browse the repository at this point in the history
  • Loading branch information
huettenhain committed Jan 17, 2025
1 parent 621511b commit 09fa07b
Showing 1 changed file with 18 additions and 15 deletions.
33 changes: 18 additions & 15 deletions refinery/lib/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
import re
import uuid

from refinery.lib.types import ByteStr


class JSONEncoderExMeta(type):
"""
Expand Down Expand Up @@ -92,9 +94,9 @@ def handled(cls, obj) -> bool:
return False


class _BytesEncode(JSONEncoderEx):
class BytesEncoder(JSONEncoderEx):
"""
This JSON Encoder encodes byte strings as arrays of integers.
A base class for JSON encoders that can encode byte arrays.
"""

@classmethod
Expand All @@ -105,30 +107,31 @@ def _is_byte_array(cls, obj) -> bool:
def handled(cls, obj) -> bool:
return cls._is_byte_array(obj) or super().handled(obj)

def encode_bytes(self, obj: ByteStr):
raise NotImplementedError

class BytesAsArrayEncoder(_BytesEncode):
"""
This JSON Encoder encodes byte strings as arrays of integers.
"""
def default(self, obj):
if self._is_byte_array(obj):
return self.encode_raw('[{}]'.format(','.join(str(b) for b in obj)))
return self.encode_bytes(obj)
return super().default(obj)


class BytesAsStringEncoder(_BytesEncode):
class BytesAsArrayEncoder(BytesEncoder):
"""
This JSON Encoder encodes byte strings as escaped strings.
This JSON Encoder encodes byte strings as arrays of integers.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def encode_bytes(self, obj: ByteStr):
return self.encode_raw('[{}]'.format(','.join(str(b & 0xFF) for b in obj)))

def default(self, obj):

class BytesAsStringEncoder(BytesEncoder):
"""
This JSON Encoder encodes byte strings as escaped strings.
"""
def encode_bytes(self, obj: ByteStr):
if isinstance(obj, memoryview):
obj = bytes(obj)
if self._is_byte_array(obj):
return obj.decode('latin1')
return super().default(obj)
return obj.decode('latin1')


def flattened(data: dict, prefix='', separator='.') -> List[Tuple[str, Union[int, float, str]]]:
Expand Down

0 comments on commit 09fa07b

Please sign in to comment.