json.loads() should return a more specific error

Roy Smith roy at panix.com
Wed Jun 27 08:45:48 EDT 2012


Before I go open an enhancement request, what do people think of the 
idea that json.load() should return something more specific than 
ValueError?

I've got some code that looks like

    try:
        response = requests.get(url)
    except RequestException as ex:
        logger.exception(ex)
        return []
    data = response.text
    try:
        events = json.loads(data)
    except ValueError as ex:
        logger.error("%s: %r", ex, data)
        return []

This would be so much neater if json would return something I could 
identify as a json error.  It would all just collapse into:

    try:
        events = requests.get(url).json
    except (RequestException, JSONDecodeError) as ex:
        logger.exception(ex)
        return []
 
We could make JSONDecodeError a subclass of ValueError so existing code 
would continue to work.



More information about the Python-list mailing list