亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

自定義 JSON 編碼器引發“對象不可 JSON 可序列化”錯誤

自定義 JSON 編碼器引發“對象不可 JSON 可序列化”錯誤

ITMISS 2023-09-12 18:27:27
我正在嘗試為我的一個類創建一個自定義 JSON 編碼器。我創建了一個簡化版本來嘗試該方法并且它有效,但是當我在項目中應用該方法時,它不斷拋出錯誤:    json.dump(obj=self.tree, fp=f, cls=BookmarkEncoder, ensure_ascii=False)  File "/usr/lib/python3.8/json/__init__.py", line 179, in dump    for chunk in iterable:  File "/usr/lib/python3.8/json/encoder.py", line 438, in _iterencode    o = _default(o)  File "/usr/lib/python3.8/json/encoder.py", line 179, in default    raise TypeError(f'Object of type {o.__class__.__name__} 'TypeError: Object of type HTMLBookmark is not JSON serializable我試圖轉換的對象是BeautifulSoupTag類的修改版本,該類的代碼如下:class HTMLBookmark(Tag, Node):    """TreeBuilder class, used to add additional functionality to the    BeautifulSoup Tag class. The following functionality is added:    - add id to each folder("h3")/url("a") being imported    - add property access to the Tag class' attributes      (date_added, icon, icon_uri, id, index, title, type and url)      which are usually found in the 'self.attrs' dictionary.    - add a setter for (id, index and title)    - redirect the self.children from an iterator iter(self.contents)    to a list (self.contents) directly"""    counter = itertools.count(start=2)    def __init__(self, *args, **kwargs):        super().__init__(*args, **kwargs)        if self.name in ("a", "h3"):            if not self.attrs.get("id"):                self.attrs["id"] = next(__class__.counter)    @property    def date_added(self):        date_added = self.attrs.get("add_date")        if not date_added:            date_added = round(time.time() * 1000)        return int(date_added)    @property    def icon(self):        return self.attrs.get("icon")    @property    def icon_uri(self):        return self.attrs.get("iconuri")    @property    def id(self):        return self.attrs.get("id")    @id.setter    def id(self, new_id):        self.attrs["id"] = new_id    @property    def index(self):        return self.attrs.get("index")    @index.setter    def index(self, new_index):        self.attrs["index"] = new_index
查看完整描述

1 回答

?
慕勒3428872

TA貢獻1848條經驗 獲得超6個贊

看起來你有一個錯字:def defaut(self, o):應該是def default(self, o):



查看完整回答
反對 回復 2023-09-12
  • 1 回答
  • 0 關注
  • 225 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號