当我尝试运行下面的代码时,最初出现以下错误 -
Error:-the JSON object must be str, not 'bytes'
import urllib.request
import json
search = '230 boulder lane cottonwood az'
search = search.replace(' ','%20')
places_api_key = 'AIzaSyDou2Q9Doq2q2RWJWncglCIt0kwZ0jcR5c'
url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query='+search+'&key='+places_api_key
json_obj = urllib.request.urlopen(url)
data = json.load(json_obj)
for item in data ['results']:
print(item['formatted_address'])
print(item['types'])
在进行一些故障排除更改后,例如:-
json_obj = urllib.request.urlopen(url)
obj = json.load(json_obj)
data = json_obj .readall().decode('utf-8')
Error - 'HTTPResponse' object has no attribute 'decode'
我收到了上面的错误,我在 stackoverflow 上尝试了多个帖子,似乎没有任何效果。我已经上传了整个工作代码,如果有人可以让它工作,我将不胜感激。我不明白的是,为什么同样的事情对其他人有效而不是我。
谢谢!
最佳答案
urllib.request.urlopen
返回 HTTPResponse
不能直接 json 解码的对象(因为它是一个字节流)
所以你会想要:
# Convert from bytes to text
resp_text = urllib.request.urlopen(url).read().decode('UTF-8')
# Use loads to decode from text
json_obj = json.loads(resp_text)
但是,如果您打印
resp_text
从您的示例中,您会注意到它实际上是 xml,因此您需要一个 xml 阅读器:resp_text = urllib.request.urlopen(url).read().decode('UTF-8')
(Pdb) print(resp_text)
<?xml version="1.0" encoding="UTF-8"?>
<PlaceSearchResponse>
<status>OK</status>
...
更新(python3.6+)
在python3.6+中,
json.load
可以采用字节流(而 json.loads
可以采用字节串)这是现在有效的:
json_obj = json.load(urllib.request.urlopen(url))
关于json - HTTPResponse' 对象没有属性 'decode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35245430/