import json
import io


def parse_header_json(
        header,
        key_mod=lambda x: x,
        value_mod=lambda x: x
):
    """
    Parse an HTTP header returning a dict where the headers are the keys and
    the values are the values

    Parameters
    ----------
    header : str or list
        HTTP header to parse, either as a string containing json or as a list
        of dicts with 'h' and 'v' keys
    key_mod : callable, optional
        Function mapping str to str that modifies the header names
    value_mod : callable, optional
        Function mapping str to str that modifies the header values

    Returns
    -------
    data : dict
        dict with header names as keys and header values as values
    """
    if not isinstance(header, str):
        raise ValueError("header has type '%s'- expected str" % type(header))
    try:
        header_json_parsed = json.load(io.StringIO(header))
    except ValueError:
        return None
    return {
        key_mod(_header['h']): value_mod(_header['v'])
        for _header in header_json_parsed
    }