我正在尝试为我的一个类创建一个自定义 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
慕勒3428872
相关分类