我正在嘗試為我的一個(gè)類創(chuàng)建一個(gè)自定義 JSON 編碼器。我創(chuàng)建了一個(gè)簡(jiǎn)化版本來嘗試該方法并且它有效,但是當(dāng)我在項(xiàng)目中應(yīng)用該方法時(shí),它不斷拋出錯(cuò)誤: 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我試圖轉(zhuǎn)換的對(duì)象是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貢獻(xiàn)1848條經(jīng)驗(yàn) 獲得超6個(gè)贊
看起來你有一個(gè)錯(cuò)字:def defaut(self, o):
應(yīng)該是def default(self, o):
添加回答
舉報(bào)
0/150
提交
取消