ERROR程序出错,错误原因:'bytes' object has no attribute 'read'

使用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()

发布了78 篇原创文章 · 获赞 31 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_37209590/article/details/104929491