编程语言
首页 > 编程语言> > Python错误加载谷歌API的JSON代码

Python错误加载谷歌API的JSON代码

作者:互联网

我正在使用谷歌地理编码API来使用Python 3.5测试以下Python代码.但是收到以下错误.代码是从Coursera的示例代码中复制的.我们假设能够测试任何位置.例如:密歇根州安娜堡

在加载JSON代码时有任何关于我为什么会遇到错误的想法:

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))

解决方法:

所以,我必须修改你的代码才能运行.我在Ubuntu 14.04上使用Python 3.4.3.

#import urllib  
import urllib.parse
import urllib.request

我收到了类似的错误:

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)

基本上,我们不是尝试解码有效的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)

Source

标签:json,python,google-geocoding-api
来源: https://codeday.me/bug/20190611/1220811.html