Request returns bytes and I'm failing to decode them

koda gates picture koda gates · Jul 29, 2015 · Viewed 40.3k times · Source

Essentially I made a request to a website and got a byte response back: b'[{"geonameId:"703448"}..........'. I'm confused because although it is of type byte, it is very human readable and appears like a list of json. I do know that the response is encoded in latin1 from running r.encoding which returned ISO-859-1 and I have tried to decode it, but it just returns an empty string. Here's what I have so far:

r = response.content
string = r.decode("ISO-8859-1")
print (string)

and this is where it prints a blank line. However when I run

len(string)

I get: back 31023 How can I decode these bytes without getting back an empty string?

Answer

mzc picture mzc · Jul 29, 2015

Did you try to parse it with the json module?

import json
parsed = json.loads(response.content)