HTTPResponse' 对象没有属性 'decode

HTTPResponse' object has no attribute 'decode

我最初在尝试 运行 下面的代码时收到以下错误-

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'

我收到上面的错误,我在 Whosebug 上尝试了多个帖子,但似乎没有任何效果。我已经上传了整个工​​作代码,如果有人能让它工作,我将不胜感激。我不明白的是,为什么同样的事情对其他人有效,而不是我。 谢谢!

urllib.request.urlopen returns 无法直接 json 解码的 HTTPResponse 对象(因为它是字节流)

所以你会想要:

# 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 reader:

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