TypeError: the JSON object must be str, not 'bytes'
發生於 json.loads(r1.read()),因 http.client.HTTPResponse.read() 回傳 bytes,Python 3 json.loads 要求 str。
# 方式一:解碼為字串
data = r1.read().decode('utf-8') # 或依回應頭 charset
result = json.loads(data)
# 方式二:直接使用 json.load(接受檔案類物件)
import json
result = json.load(r1) # r1 為 HTTPResponse,實現了 read(),但需注意編碼
def getIpCountry(ip):
conn.request('GET', '/service/getIpInfo.php?ip=%s' % ip)
r1 = conn.getresponse()
if r1.status == 200:
# 讀取並解碼
body = r1.read().decode('utf-8')
return json.loads(body)['data']
else:
return "Error"
requests 庫簡化:r = requests.get(url); data = r.json() 自動處理編碼與解析。pandas.read_csv 或 awk/sed 前置過濾再進入 Python。HTTPConnection 可保持長連線,但需處理逾時與異常重連。核心修正:bytes → decode('utf-8') → str → json.loads。