Dealing with non-trivial key types when defining JSON encoder

Hi,

I have a dictionary whose keys are not strings but PosixPath and I am trying to define a custom encoder to be able to dump them to JSON with

def object_to_string(obj : Any, sort_keys=False) -> str:
    '''
    Parameters
    -------------------
    obj: Python object, e.g. dictionary, it can contain the following objects:
    - Path (pathlib) 
    - DictConfig (omegacong)
    sort_keys: If true will sort the keys of all the dictionaries. Not recommended for mixed type keys

    Returns
    -------------------
    JSON string
    '''
    def default_encoder(x):
        if isinstance(x, DictConfig):
            return OmegaConf.to_container(cfg=x, resolve=True)

        if isinstance(x, Path):
            return str(x)

        log.info(x)
        raise TypeError(f"Unserializable type: {type(x)}")

    try:
        json_string = json.dumps(obj, sort_keys=sort_keys, default=default_encoder)
    except Exception as exc:
        raise RuntimeError(f'Cannot covert to JSON string: {obj}') from exc

    return json_string

But this seems to only work for the values, not the keys. I see an old discussion here about that and I wonder if there is proper way to do this nowdays

Cheers.

1 Like