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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM