import json
import urllib.request, urllib.error, urllib.parse
Name = 'BagFullOfHoles' #Random player
Platform = 'xone'#pc, xbox, xone, ps4, ps3
url = 'http://api.bfhstats.com/api/playerInfo?plat=' + Platform + '&name=' + Name
json_obj = urllib.request.urlopen(url)
data = json.load(json_obj)
print (data)
TypeError: can't use a string pattern on a bytes-like object
Just recently used 2to3.py and this error or others come up when I try to fix it . Anyone with any pointers?
The
json_obj = urllib.request.urlopen(url)
returns an HTTPResponse object. We need toread()
the response bytes in, and thendecode()
those bytes to a string as follows:Python 3, as you may know, has separate
bytes
andstr
types. Reading from a file opened in binary mode will returnbytes
objects.The
json.load()
function only works with files (and file-like objects) opened in text mode (as opposed to binary mode). It appears thaturllib.request.urlopen()
will return a file-like in binary mode.Instead of using
json.load()
, consider reading from theHTTPResponse
object and decoding, then passing tojson.loads()
, like this:Alternatively, you may wish to investigate the requests module.