Python JSON: raise JSONDecodeError from parse_constant

257 Views Asked by At

I am currently using the json module to load some JSON content and I need to exclude NaN values. The standard way to do this seems to be to implement a parse_constant method and then pass this method to json.loads.

Example:

def parse_constant(c: str) -> float:
    if c == "NaN":
        raise ValueError("NaN is not valid JSON")
    return float(c)

json_content = json.loads(some_json_string, parse_constant=parse_constant)

Apparently, the decode implementation does not catch the ValueError and transform it into a JSONDecodeError, which forces me to check for both exception types. I miss the context (line number, JSON document) to build the decode error myself. I know I could just catch ValueError, but is there a way to configure the json module to raise what I would expect to be the logical exception type?

0

There are 0 best solutions below