Python 3, let json object accept bytes or let urlopen output strings
Question: With Python3 I am requesting from some url a json document.

    
    
    response = urllib.request.urlopen(request)
    

The `response` object is a file like object with read, readline functions.

Normally a json object can be created with a file (opened in textmode)

    
    
    obj = json.load(fp)
    

What I would like to do is:

    
    
    obj = json.load(response)
    

this however does not work as urlopen returns a file object in binary mode.

A work around is of course:

    
    
    str_response = response.readall().decode('utf-8')
    obj = json.loads(str_response)
    

but this feels bad...

Is there a better way that I can transform a byte file object to a string file
object? Or am I missing any parameters for either `urlopen` or `json.load` to
give an encoding?

This would look to me as a common use case so I'm confident I'm missing some
usefull function.


Answer: Python’s wonderful standard library to the rescue…

    
    
    import codecs
    
    reader = codecs.getreader("utf-8")
    obj = json.load(reader(response))
    

Works with both py2 and py3.

