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, stream: circuitpython_typing.ByteStream, *, default: Union[Callable[[object], None], None] = None) None ¶
Output object to stream in msgpack format.