Python错误加载google API的JSON代码

标签 python json google-geocoding-api

我正在使用 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/

相关文章:

python - 使用 tf.estimator.Estimator 框架进行迁移学习

python - 类型错误 : issubclass() arg 2 must be a class or tuple of classes

javascript - 从位置获取位置

python - 在写入 CSV 文件时从中读取

python - 数据类不从其父级继承 __eq__() 方法

php - 有没有一种可靠的方法来检测 php 中字符串中的 base64 编码?

json - psql在字符串中插入带有双引号的json

c# - MongoDB .NET 驱动程序 - 将 lambda 表达式转换为 JSON 对象

javascript - 从邮政编码谷歌地理编码获取城市名称

google-apps-script - 在 Apps 脚本中使用撇号对位置进行地理编码会出现 'Action not allowed' 错误