Andrew Quoc-Anh Ho Andrew Quoc-Anh Ho - 1 year ago 253
JSON Question

Why is it giving me the error, "the JSON object must be str, not 'bytes'", and how do I fix it?

I was following a tutorial about how to use JSON objects (link: When they ran the code, they got no errors, but I did. Is it something to do with different Python versions or something?

from urllib.request import urlopen
import json

def printResults(data):
theJSON = json.loads(data)
print (theJSON)

def main():
urlData =""

webUrl = urlopen(urlData)
if (webUrl.getcode()==200):
data =
print ("You failed")


Answer Source

The HTTPResponse object returned from urlopen reads bytes data (raw binary data), not str data (textual data), while the json module works with str. You need to know (or inspect the headers to determine) the encoding used for the data received, and decode is appropriately before using json.loads.

Assuming it's UTF-8 (most websites are), you can just change:

data =


data ='utf-8')

and it should fix your problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download