msgpack
– Pack object in msgpack format¶
The msgpack format is similar to json, except that the encoded data is binary. See https://msgpack.org for details. The module implements a subset of the cpython module msgpack-python.
Not implemented: 64-bit int, uint, float.
Example 1:
import msgpack
from io import BytesIO
b = BytesIO()
msgpack.pack({'list': [True, False, None, 1, 3.14], 'str': 'blah'}, b)
b.seek(0)
print(msgpack.unpack(b))
Example 2: handling objects:
from msgpack import pack, unpack, ExtType
from io import BytesIO
class MyClass:
def __init__(self, val):
self.value = val
def __str__(self):
return str(self.value)
data = MyClass(b'my_value')
def encoder(obj):
if isinstance(obj, MyClass):
return ExtType(1, obj.value)
return f"no encoder for {obj}"
def decoder(code, data):
if code == 1:
return MyClass(data)
return f"no decoder for type {code}"
buffer = BytesIO()
pack(data, buffer, default=encoder)
buffer.seek(0)
decoded = unpack(buffer, ext_hook=decoder)
print(f"{data} -> {buffer.getvalue()} -> {decoded}")
Available on these boards
- msgpack.pack(obj: object, buffer: _typing.WriteableBuffer, *, default: Callable[[object], None] | None = None) None ¶
Ouput object to buffer in msgpack format.
- Paramètres:
obj (object) – Object to convert to msgpack format.
buffer (WriteableBuffer) – buffer to write into
default (Optional[Callable[[object], None]]) – function called for python objects that do not have a representation in msgpack format.
- msgpack.unpack(buffer: _typing.ReadableBuffer, *, ext_hook: Callable[[int, bytes], object] | None = None, use_list: bool = True) object ¶
Unpack and return one object from buffer.
- Paramètres:
buffer (ReadableBuffer) – buffer to read from
ext_hook (Optional[Callable[[int, bytes], object]]) – function called for objects in msgpack ext format.
use_list (Optional[bool]) – return array as list or tuple (use_list=False).
- Return object:
object read from buffer.