fedbiomed.common.json

Module: fedbiomed.common.json

This module defines message serializer and deserializer for sending / receiving / parsing messages through Messaging.

Compared to the usual json module, it deals with some fedbiomed data types which are not serialized by default (eg: enumerations)

Functions

deserialize_msg(msg)

Deserializes a JSON string or bytes message as a dictionary.

Parameters:

Name Type Description Default
msg Union[str, bytes]

message in JSON format but encoded as string or bytes

required

Returns:

Type Description
dict

Parsed message as python dictionary.

Source code in fedbiomed/common/json.py
def deserialize_msg(msg: Union[str, bytes]) -> dict:
    """Deserializes a JSON string or bytes message as a dictionary.

    Args:
        msg: message in JSON format but encoded as string or bytes
    Returns:
        Parsed message as python dictionary.
    """
    decode = json.loads(msg)

    # deserialize our own types/classes
    decode = _deserialize_test_metric(decode)

    # errnum is present in ErrorMessage and is an Enum
    # which need to be deserialized
    if 'errnum' in decode:
        errnum = decode['errnum']
        found = False
        for e in ErrorNumbers:
            if e.value == errnum:
                found = True
                decode['errnum'] = e
                break
        if not found:
            # error code sent by the node is unknown
            decode['errnum'] = ErrorNumbers.FB999

    return decode

serialize_msg(msg)

Serialize an object as a JSON message (applies for dict-like objects)

Parameters:

Name Type Description Default
msg dict

dict-like object containing the message to send.

required

Returns:

Type Description
str

JSON parsed message ready to transmit.

Source code in fedbiomed/common/json.py
def serialize_msg(msg: dict) -> str:
    """Serialize an object as a JSON message (applies for dict-like objects)

    Args:
        msg: dict-like object containing the message to send.

    Returns:
        JSON parsed message ready to transmit.
    """

    # serialize our own types/classes
    msg = _serialize_training_args(msg)
    msg = _serialize_test_metric(msg)

    # Errnum is present in ErrorMessage and is an Enum
    # which need to be serialized

    if 'errnum' in msg:
        msg['errnum'] = msg['errnum'].value
    return json.dumps(msg)