为了账号安全,请及时绑定邮箱和手机立即绑定

自定义 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 关注
  • 173 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信