三多
技术领域的难题往往代表着经典 而我只是一个伪技术宅!!!

使用json解析数据时,通常遇到这里就会出现问题'bytes' object has no attribute 'read',这是由于使用的json内置函数不同,一个是load另一个是loads。

import urllib.request
import json

response = urllib.request.urlopen('http://www.reddit.com/r/all/top/.json').read()
jsonResponse = json.load(response)

for child in jsonResponse['data']['children']:
    print (child['data']['title'])

通常解决方式有两种,一种是更改函数为loads,另一种是更改编码格式为utf8

第一种解决方式:

jsonResponse = json.loads(response.decode('utf-8'))

第二种解决方式

使用json.loads()而不是json.load()

内容参考:https://stackoverflow.com/questions/6541767/python-urllib-error-attributeerror-bytes-object-has-no-attribute-read

posted on 2017-10-14 18:33  SanDuo1314  阅读(27701)  评论(0编辑  收藏  举报