首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Python 分析 Apache 日誌:JSON 解碼 bytes 錯誤修正

     編輯:程式設計疑難解答

錯誤訊息

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(),但需注意編碼

完善的 getIpCountry 函式

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。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved