I am using google geocode API to test the following Python3.5 code but receive the error below.
raise JSONDecodeError("Expecting value", s, err.value) from None >JSONDecodeError: Expecting value
Here are the codes:
import urllib
import json
serviceurl = 'http://maps.googleapis.com/maps/api/geocode/json?'
while True:
address = input('Enter location: ')
if len(address) < 1 : break
url = serviceurl + urllib.parse.urlencode({'sensor':'false',
'address': address})
print ('Retrieving', url)
uh = urllib.request.urlopen(url)
data = uh.read()
print ('Retrieved',len(data),'characters')
js = json.loads(str(data))
Any idea about why I have the error.
The error arises because the "data" is of type bytes so you have to decode it into a string before using json.loads
to turn it into a json object. So to solve the problem:
uh = urllib.request.urlopen(url)
data = uh.read()
print ('Retrieved',len(data),'characters')
js = json.loads(data.decode("utf-8"))
Also, str(data) in the code you share will work in Python 2.x but not in Python 3.x because str() doesn't turn bytes into a string in 3.x.