import base64


def _encode_bytes_if_required(data):
    """
    If the specified data is represented as bytes, convert it to a UTF8 string (using Base64 encoding if the bytes do not represent valid UTF8).

    This is needed because json.dumps cannot serialise bytes.

    :param data: The data to encode.
    :return: If the data is represented as bytes, an equivalent UTF8 or Base64-encoded string; otherwise, the original data.
    """

    if (not isinstance(data, bytes)):
        return data

    try:
        data = data.decode('utf8')
    except UnicodeDecodeError:
        data = base64.encodebytes(data).decode('ascii')

    return data