2015/09/22

Python urlopen TypeError: the JSON object must be str, not 'bytes'


原來的程式碼為:
# -*- coding: utf-8 -*-

from urllib import request
url = "http://data.kaohsiung.gov.tw/Opendata/DownLoad.aspx?Type=2&CaseNo1=AP&CaseNo2=17&FileType=2&Lang=C&FolderType="
data = request.urlopen(url).read()


只要將read後方加上decode('utf8')即可
# -*- coding: utf-8 -*-

from urllib import request
url = "http://data.kaohsiung.gov.tw/Opendata/DownLoad.aspx?Type=2&CaseNo1=AP&CaseNo2=17&FileType=2&Lang=C&FolderType="
data = request.urlopen(url).read().decode('utf8')
print (data)