2. Object serialisation

The Assembly class provides a means of saving your objects to JSON format. They are saved with type information so that you can load them back again as Python objects.

class turberfield.utils.assembly.Assembly
static register(*args, namespace=None)

Call this function to register your classes for Assembly.

Returns a list of the types so far registered.

In order to create objects from JSON, your types must support construction semantics with keyword arguments (ie: MyClass(**kwargs)).

If this is not possible (as in the case of Enums), then define a classmethod called factory which will be used instead, eg:

class Colour(enum.Enum):
    red = (255, 0 , 0)
    green = (0, 255 , 0)
    blue = (0, 0 , 255)

    @classmethod
    def factory(cls, name=None, **kwargs):
        return cls[name]


Assembly.register(Colour)
static dump(obj, fp, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kwargs)

Serialize obj as a JSON formatted stream to fp.

This function is compatible with json.dump from Python’s standard library, and accepts the same arguments.

static dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kwargs)

Serialize obj to a JSON formatted string.

This function is compatible with json.dumps from Python’s standard library, and accepts the same arguments.

static loads(s)

Deserialize a JSON string to Python object(s). Those types you have registered will be recognised and used to create the deserialised objects.