import re
import json


def _find_and_read_row(log_str : str, key : str, row_must_exist=True):
    """
    Finds first matching row in a log file string and converts it into a dict.
    """
    regex = r'.*"key": "{}".*'.format(key)
    row = re.search(regex, log_str)
    if row is None:
        if(row_must_exist):
            raise Exception('Failed to match regex: '.format(regex))
        else:
            return None
    row = json.loads(row.group(0))
    row.pop('key')
    return row