Function return application on function

Hello all. I’m (primarily) a Java guy learning Python and trying to wrap my head around something here. For the below API call I’m wondering why o.read() is not acceptable in place of the raw byte variable here, even when wrapped.

-Can someone help me here? Why would this be so?

Thanks!


import urllib.request
import json

o = urllib.request.urlopen(
    urllib.request.Request("http://globalmentoring.com.mx/api/personas.json", data=None, headers={
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.47 Safari/537.36'}
    )
)
raw = o.read()
print(type(o.read())) #bytes
print(type(raw)) #bytes
json.loads(raw.decode("utf-8")) #works
json.loads(o.read().decode("utf-8")) #boom
json.loads((o.read()).decode("utf-8")) #boom

What is the error you’re seeing?

In the literal code you’ve posted here, after you call o.read() the data will be exhausted, and future calls to read will return an empty result (i.e. b"", an empty bytes array). That’s going to cause an error in json.loads because an empty input is not valid JSON.

But that might not be the issue, it depends on what you’re actually doing to get the error.

3 Likes

Yes! I didn’t realize it behaved similar to a DB cursor with advancing reads. Slaps forehead

Thank you.

1 Like