Encoder class

class rapidjson.Encoder(skip_invalid_keys=False, ensure_ascii=True, write_mode=WM_COMPACT, indent=4, sort_keys=False, number_mode=None, datetime_mode=None, uuid_mode=None, bytes_mode=BM_UTF8, iterable_mode=IM_ANY_ITERABLE, mapping_mode=MM_ANY_MAPPING)

Class-based dumps()-like functionality.

Parameters

Attributes

bytes_mode
Type

int

How bytes values should be treated.

datetime_mode
Type

int

Whether and how datetime values should be encoded.

ensure_ascii
Type

bool

Whether the output should contain only ASCII characters.

indent_char
Type

str

What will be used as end-of-line character.

indent_count
Type

int

The indentation width.

iterable_mode
Type

int

Whether iterables will be generically encoded as JSON arrays or not.

mapping_mode
Type

int

Whether mappings will be generically encoded as JSON objects or not.

number_mode
Type

int

The encoding behavior with regards to numeric values.

skip_invalid_keys
Type

bool

Whether invalid keys shall be skipped.

Note

skip_invalid_keys is a backward compatible alias of new MM_SKIP_NON_STRING_KEYS mapping mode.

sort_keys
Type

bool

Whether dictionary keys shall be sorted alphabetically.

Note

sort_keys is a backward compatible alias of new MM_SORT_KEYS mapping mode.

uuid_mode
Type

int

Whether and how UUID values should be encoded

write_mode
Type

int

Whether the output should be pretty printed or not.

Methods

__call__(obj, stream=None, *, chunk_size=65536)
Parameters
  • obj – the value to be encoded

  • stream – a file-like instance

  • chunk_size (int) – write the stream in chunks of this size at a time

Returns

a string with the JSON encoded value, when stream is None

When stream is specified, the encoded result will be written there, possibly in chunks of chunk_size bytes at a time, and the return value will be None.

default(value)
Parameters

value – the Python value to be encoded

Returns

a JSON-serializable value

If implemented, this method is called whenever the serialization machinery finds a Python object that it does not recognize: if possible, the method should returns a JSON encodable version of the value, otherwise raise a TypeError:

>>> class Point:
...   def __init__(self, x, y):
...     self.x = x
...     self.y = y
...
>>> point = Point(1,2)
>>> Encoder()(point)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: <__main__.Point object at …> is not JSON serializable
>>> class PointEncoder(Encoder):
...   def default(self, obj):
...     if isinstance(obj, Point):
...       return {'x': obj.x, 'y': obj.y}
...     else:
...       raise TypeError('%r is not JSON serializable' % obj)
...
>>> pe = PointEncoder(sort_keys=True)
>>> pe(point)
'{"x":1,"y":2}'

When you want to treat your bytes instances in a special way, you can use BM_NONE together with this method:

>>> class HexifyBytes(Encoder):
...   def default(self, obj):
...     if isinstance(obj, bytes):
...       return obj.hex()
...     else:
...       return obj
...
>>> small_numbers = bytes([1, 2, 3])
>>> hb = HexifyBytes(bytes_mode=BM_NONE)
>>> hb(small_numbers)
'"010203"'

Likewise, when you want full control on how an iterable such as a tuple should be encoded, you can use IM_ONLY_LISTS and implement a suitable default() method:

>>> from time import localtime, struct_time
>>> class ObjectifyStructTime(Encoder):
...   def default(self, obj):
...     if isinstance(obj, struct_time):
...       return {'__class__': 'time.struct_time', '__init__': list(obj)}
...     else:
...       raise ValueError('%r is not JSON serializable' % obj)
...
>>> obst = ObjectifyStructTime(iterable_mode=IM_ONLY_LISTS)
>>> obst(localtime()) 
'[2020,11,28,19,55,40,5,333,0]'

Similarly, when you want full control on how a mapping other than plain dict should be encoded, you can use MM_ONLY_DICTS and implement a default() method:

>>> from collections import OrderedDict
>>> class ObjectifyOrderedDict(Encoder):
...   def default(self, obj):
...     if isinstance(obj, OrderedDict):
...       return {'__class__': 'collections.OrderedDict',
...               '__init__': list(obj.items())}
...     else:
...       raise ValueError('%r is not JSON serializable' % obj)
...
>>> ood = ObjectifyOrderedDict(mapping_mode=MM_ONLY_DICTS)
>>> ood(OrderedDict((('a', 1), ('b', 2))))
'{"__class__":"collections.OrderedDict","__init__":[["a",1],["b",2]]}'