I know there are tons of this exact question on here but I can't find an answer.
I'm trying to use the Google Maps API for Geocoding to go through a list of sloppy addresses, and get formatted addresses.
I have this exact code from the Google documentation:
import urllib2
address="1600+Amphitheatre+Parkway,+Mountain+View,+CA"
url="https://maps.googleapis.com/maps/api/geocode/json?address=%s" % address
response = urllib2.urlopen(url)
jsongeocode = response.read()
It then says that jsongeocode
is a JSON object. However, from what I've gathered from looking online is that this IS NOT a JSON object yet. If i'm wrong here and it is a JSON object, how do I parse it?
If I call print(jsongeocode)
it prints what appears to be a JSON object with the proper attributes in my terminal.
So I try to convert the jsongeocode
object to a JSON object:
jdata = json.load(jsongeocode)
This gives me this error:
AttributeError: 'bytes' object has no attribute 'read'
EDIT
I've switched the json function call to jdata = json.loads(jsongeocode)
, but now the error I get is this:
TypeError: The JSON Object must be str, not 'bytes'
Your code works fine in Python 2. You just need to parse the JSON string returned by the API using
json.loads(jsongeocode)
.The error message
TypeError: The JSON Object must be str, not 'bytes'
suggests to me that you are using Python 3. However, you are importing theurllib2
module which is only present in Python 2. I'm not sure how you achieved that. Anyway, assuming Python 3:So there is the exception that you have seen. The response contained in
json_byte_string
is a byte string - it is of classbytes
, however, in Python 3json.loads()
expects astr
which is a Unicode string. So you need to convertjson_byte_string
from a byte string to Unicode. To do that requires that you know the encoding of the byte string. Here I use UTF8 because that is what was specified in theContent-Type
response header:Now it can be passed to
json.loads()
:And there you have the decoded JSON string as a dictionary. The formatted address is available as:
There is a better way to do this: use
requests
:Much better!