我正在使用 google geocode API 测试以下 Python3.5 代码,但收到以下错误。
raise JSONDecodeError("Expecting value", s, err.value) from None >JSONDecodeError: Expecting value
代码如下:
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))
关于为什么我有错误的任何想法。
最佳答案
错误的产生是因为“数据”是bytes类型,所以在使用json.loads
把它变成json对象之前,你必须把它解码成一个字符串。所以解决问题:
uh = urllib.request.urlopen(url)
data = uh.read()
print ('Retrieved',len(data),'characters')
js = json.loads(data.decode("utf-8"))
此外,您共享的代码中的 str(data) 可以在 Python 2.x 中使用,但不能在 Python 3.x 中使用,因为 str() 不会在 3.x 中将字节转换为字符串。
关于Python错误加载google API的JSON代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34573197/