import json


def add_metadata_to_table(table, metadata, key='my_metadata'):
    """
    Add json metadata to a pyarrow.Table under a given key

    Notes
    -----
    Based on: https://stackoverflow.com/a/58978449/709975
    """
    # convert dictionary to json representation (str object),
    # then convert it to a bytes object encoded in utf-8
    metadata_b = json.dumps(metadata).encode('utf-8')

    # the key also has to be converted to bytes
    key = bytes(key, encoding='utf-8')

    # take old table's metadata (if any) and append
    # a new key with our metadata under the "my_metadata" key
    new_schema_metadata = {**{key: metadata_b}, **table.schema.metadata}

    # replace old metadata with the new version
    table_w_metadata = table.replace_schema_metadata(new_schema_metadata)
    return table_w_metadata