HTTPResponse'对象没有属性'decode

时间:2016-02-06 19:28:28

标签: json python-3.4 urllib

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

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上尝试过多个帖子似乎没什么用。我上传了整个工​​作代码,如果有人能让它工作,我将非常感激。我不明白的是,为什么同样的事情对别人而不是我有用。 谢谢!

1 个答案:

答案 0 :(得分:11)

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