Gav*_*vin 5 python json google-geocoding-api
我正在使用谷歌地理编码API来使用Python 3.5测试以下Python代码.但是收到以下错误.代码是从Coursera的示例代码中复制的.我们假设能够测试任何位置.例如:密歇根州安娜堡
在加载JSON代码时有任何关于我为什么会遇到错误的想法:
从None> JSONDecodeError中提出JSONDecodeError("期望值",s,err.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))
Run Code Online (Sandbox Code Playgroud)
小智 9
看一下错误:
"从 None 引发 JSONDecodeError("期望值", s, err.value)
JSONDecodeError:期望值”
意思是说,当我应该得到一些东西时,我却得到了“无”。
在调用之前检查您的数据变量是否为“无” json.loads()。
if data == None or data == '':
print('I got a null or empty string value for data in a file')
else:
js = json.loads(str(data))
Run Code Online (Sandbox Code Playgroud)
出现错误的原因是"数据"是字节类型,因此在使用json.loads它将其转换为json对象之前必须将其解码为字符串.所以要解决这个问题:
uh = urllib.request.urlopen(url)
data = uh.read()
print ('Retrieved',len(data),'characters')
js = json.loads(data.decode("utf-8"))
Run Code Online (Sandbox Code Playgroud)
此外,您共享的代码中的str(data)将在Python 2.x中工作,但在Python 3.x中不起作用,因为str()不会将字节转换为3.x中的字符串.
小智 3
所以,我必须修改你的代码才能运行。我在 Ubuntu 14.04 上使用 Python 3.4.3。
#import urllib
import urllib.parse
import urllib.request
Run Code Online (Sandbox Code Playgroud)
我收到了类似的错误:
heyandy889@laptop:~/src/test$ python3 help.py
Enter location: MI
Retrieving http://maps.googleapis.com/maps/api/geocode/json?sensor=false&address=MI
Retrieved 1405 characters
Traceback (most recent call last):
File "help.py", line 18, in <module>
js = json.loads(str(data))
File "/usr/lib/python3.4/json/__init__.py", line 318, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.4/json/decoder.py", line 343, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python3.4/json/decoder.py", line 361, in raw_decode
raise ValueError(errmsg("Expecting value", s, err.value)) from None
ValueError: Expecting value: line 1 column 1 (char 0)
Run Code Online (Sandbox Code Playgroud)
基本上,我们不是尝试解码有效的 json 字符串,而是尝试解码 Python 'None' 值,该值不是有效的 json。尝试修补以下示例代码。首先运行一次,以仔细检查最简单的 json 对象“{}”是否可以工作。然后,一一尝试每个不同的“possible_json_string”。
#...
print ('Retrieved',len(data),'characters')
#possible_json_string = str(data) #original error
possible_json_string = '{}' #sanity check with simplest json
#possible_json_string = data #why convert to string at all?
#possible_json_string = data.decode('utf-8') #intentional conversion
print('possible_json_string')
print(possible_json_string)
js = json.loads(possible_json_string)
Run Code Online (Sandbox Code Playgroud)