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:
skip_invalid_keys (bool) – whether invalid
dict
keys will be skippedensure_ascii (bool) – whether the output should contain only ASCII characters
write_mode (int) – enable particular pretty print behaviors
indent – either an integer, the indentation width, or a string, that will be used as line separator, when write_mode is not
WM_COMPACT
sort_keys (bool) – whether dictionary keys should be sorted alphabetically
number_mode (int) – enable particular behaviors in handling numbers
datetime_mode (int) – how should datetime, time and date instances be handled
uuid_mode (int) – how should UUID instances be handled
bytes_mode (int) – how should bytes instances be handled
iterable_mode (int) – how should iterable values be handled
mapping_mode (int) – how should mapping values be handled
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 isNone
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 useBM_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 useIM_ONLY_LISTS
and implement a suitabledefault()
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 useMM_ONLY_DICTS
and implement adefault()
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]]}'