您的代码在 Python 2 中运行良好。您只需使用 json.loads(jsongeocode) 解析 API 返回的 JSON 字符串。
错误消息 TypeError: The JSON Object must be str, not 'bytes' 向我表明您正在使用 Python 3。但是,您正在导入仅存在于 Python 2 中的 urllib2 模块。我不确定您是如何实现的。无论如何,假设 Python 3:
import json
from urllib.request import urlopen
address="1600+Amphitheatre+Parkway,+Mountain+View,+CA"
url="https://maps.googleapis.com/maps/api/geocode/json?address=%s" % address
response = urlopen(url)
json_byte_string = response.read()
>>> type(json_byte_string)
<class 'bytes'>
>>> jdata = json.loads(json_byte_string)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python3.4/json/__init__.py", line 312, in loads
s.__class__.__name__))
TypeError: the JSON object must be str, not 'bytes'
所以有你看到的例外。 json_byte_string 中包含的响应是一个字节字符串 - 它属于 bytes 类,但是,在 Python 3 中,json.loads() 需要一个 str,它是一个 Unicode 字符串。所以你需要将json_byte_string从一个字节串转换为Unicode。为此,您需要知道字节字符串的编码。这里我使用 UTF8,因为这是在 Content-Type 响应标头中指定的:
>>> response.headers['Content-Type']
'application/json; charset=UTF-8'
>>> json_string = str(json_byte_string, 'utf8')
>>> type(json_string)
<class 'str'>
现在可以传递给json.loads():
>>> jdata = json.loads(json_string)
>>> jdata
{'results': [{'types': ['street_address'], 'address_components': [{'types': ['street_number'], 'long_name': '1600', 'short_name': '1600'}, {'types': ['route'], 'long_name': 'Amphitheatre Parkway', 'short_name': 'Amphitheatre Pkwy'}, {'types': ['locality', 'political'], 'long_name': 'Mountain View', 'short_name': 'Mountain View'}, {'types': ['administrative_area_level_2', 'political'], 'long_name': 'Santa Clara County', 'short_name': 'Santa Clara County'}, {'types': ['administrative_area_level_1', 'political'], 'long_name': 'California', 'short_name': 'CA'}, {'types': ['country', 'political'], 'long_name': 'United States', 'short_name': 'US'}, {'types': ['postal_code'], 'long_name': '94043', 'short_name': '94043'}], 'formatted_address': '1600 Amphitheatre Parkway, Mountain View, CA 94043, USA', 'geometry': {'location_type': 'ROOFTOP', 'viewport': {'northeast': {'lng': -122.0828811197085, 'lat': 37.4236854802915}, 'southwest': {'lng': -122.0855790802915, 'lat': 37.4209875197085}}, 'location': {'lng': -122.0842301, 'lat': 37.4223365}}, 'place_id': 'ChIJ2eUgeAK6j4ARbn5u_wAGqWA'}], 'status': 'OK'}
您将解码后的 JSON 字符串作为字典。格式化地址为:
>>> jdata['results'][0]['formatted_address']
'1600 Amphitheatre Parkway, Mountain View, CA 94043, USA'
有一个更好的方法可以做到这一点:使用requests:
import requests
address="1600+Amphitheatre+Parkway,+Mountain+View,+CA"
url="https://maps.googleapis.com/maps/api/geocode/json?address=%s" % address
r = requests.get(url)
jdata = r.json()
>>> jdata['results'][0]['formatted_address']
'1600 Amphitheatre Parkway, Mountain View, CA 94043, USA'
好多了!