Data serialization

The qtt package contains methods to serialize objects to JSON.

[1]:
from dataclasses import dataclass
from functools import partial

import numpy as np
from dataclasses_json import dataclass_json

from qtt.utilities.json_serializer import decode_json, encode_json, qtt_serializer
[2]:
json = encode_json([1.0, 'hello'])
print(f'list of items: {json}\n')

json = encode_json(np.array([1.,2.]))
print(f'numpy array: {json}')
list of items: [1.0, "hello"]

numpy array: {"__object__": "array", "__content__": {"__ndarray__": "AAAAAAAA8D8AAAAAAAAAQA==", "__data_type__": "<f8", "__shape__": [2]}}
[3]:
decoded_array = decode_json(json)
print(decoded_array)
[1. 2.]

Custom data types

Custom data objects can be serialized by creating an encoder and decoder. For example to serialize dataclass objects with JSON we can do the following.

[4]:
@dataclass_json
@dataclass
class CustomClass():

    x : float
    y : str

mydata = CustomClass(x=1., y='hi')
print(mydata)
CustomClass(x=1.0, y='hi')

We can create custom encoding methods to make the serialization possible.

[5]:
qtt_serializer.register_dataclass(CustomClass)

json = qtt_serializer.serialize(mydata)
print(f'encoded json: {json}')

decoded_object = qtt_serializer.unserialize(json)
print(f'decoded_object: {decoded_object}')
encoded json: {"__object__": "_dataclass_CustomClass", "__content__": {"x": 1.0, "y": "hi"}}
decoded_object: CustomClass(x=1.0, y='hi')
[ ]: