json: 类型错误: '...spam...' 不能序列化为 JSON

0 投票
2 回答
1265 浏览
提问于 2025-04-18 02:23

在这个类里,我想把一些状态信息保存到一个json文件里,但当我尝试保存一个字典时,遇到了一个错误:TypeError: '<li>...stuff...</li>' is not JSON serializable

class Save(object):
    def __init__(self, MainFrameDict):
        super(Save, self).__init__()
        self.MainFrameDict = MainFrameDict
        import pdb; pdb.set_trace()
        self.writeJson()
    def writeJson(self):
        self.json_state_file = os.path.join(self.MainFrameDict['item_folder'],
                                            self.MainFrameDict['itemNumber']+'.json')
        with open(self.json_state_file,'wb') as f:
            json.dump(self.MainFrameDict['currentItemInfo'], f)
        self.printJsonStateFile()
        #import pdb; pdb.set_trace()
    def printJsonStateFile(self):
        with open(self.json_state_file,'rb') as f:
            json_data = json.loads(f)

我想保存的字典里包含:

(Pdb) print(self.MainFrameDict['currentItemInfo'].keys())
['image_list', 'description', 'specs']
(Pdb) print(self.MainFrameDict['currentItemInfo']['description'])
Run any time in the comfort of your own home. Deluxe treadmill
features 9 programs; plug in your MP3 player to rock your workout!
<ul>
<li>Horizon T101 deluxe treadmill</li>
<li>55" x 20" treadbelt</li>
<li>9 programs</li>
<li>Fan</li>
<li>Motorized incline to 10%</li>
<li>Up to 10 mph</li>
<li>Surround speakers are compatible with your MP3 player (not
included)</li>
<li>71"L x 33"W x 55"H</li>
<li>Wheels for mobility</li>
<li>Folds for storage</li>
<li>Weight limit: 300 lbs.</li>
<li>Assembly required</li>
<li>Limited warranty</li>
<li>Made in USA</li>
</ul>
(Pdb) print type(self.MainFrameDict['currentItemInfo']['description'])
<class 'bs4.BeautifulSoup'>

我正在试图弄明白的错误追踪信息:

Traceback (most recent call last):
  File "display_image.py", line 242, in onNewItemButton
Save(MainFrame.__dict__)
  File "display_image.py", line 20, in __init__
self.writeJson()
  File "display_image.py", line 24, in writeJson
json.dump(self.MainFrameDict['currentItemInfo'], f)
  File "C:\Python27\Lib\json\__init__.py", line 189, in dump
for chunk in iterable:
  File "C:\Python27\Lib\json\encoder.py", line 434, in _iterencode
for chunk in _iterencode_dict(o, _current_indent_level):
  File "C:\Python27\Lib\json\encoder.py", line 408, in _iterencode_dict
for chunk in chunks:
  File "C:\Python27\Lib\json\encoder.py", line 442, in _iterencode
o = _default(o)
  File "C:\Python27\Lib\json\encoder.py", line 184, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: Run any time in the comfort of your own home. Deluxe treadmill
features 9 programs; plug in your MP3 player to rock your workout!
<ul>
<li>Horizon T101 deluxe treadmill</li>
<li>55" x 20" treadbelt</li>
<li>9 programs</li>
<li>Fan</li>
<li>Motorized incline to 10%</li>
<li>Up to 10 mph</li>
<li>Surround speakers are compatible with your MP3 player (not
included)</li>
<li>71"L x 33"W x 55"H</li>
<li>Wheels for mobility</li>
<li>Folds for storage</li>
<li>Weight limit: 300 lbs.</li>
<li>Assembly required</li>
<li>Limited warranty</li>
<li>Made in USA</li>
</ul>
 is not JSON serializable

我查看过的文档和帖子:

我不确定这是不是因为字典是嵌套的,或者是编码/解码方面的问题。我到底在寻找什么,哪里不理解呢?有没有办法确定一个项目的编码是什么?

2 个回答

0

你可以试试这个方法。对我来说,它的成功率是100%。你可以把任何类型的Python对象,比如字典、列表、元组,甚至普通的类对象,都转换成JSON格式。

import json

class DatetimeEncoder(json.JSONEncoder):
   def default(self, obj):
       try:
        return super(DatetimeEncoder, obj).default(obj)
       except TypeError:
        return str(obj)


class JsonSerializable(object):
    def toJson(self):
        return json.dumps(self.__dict__, cls=DatetimeEncoder)

    def __repr__(self):
       return self.toJson()


class Utility(JsonSerializable):
     def __init__(self, result = object, error=False, message=''):
         self.result=result
         self.error=error
         self.message=message

最后,像这样调用Utility类,然后把它转换成JSON。

jsone = Utility()
jsone.result=result # any kind of object
json.error=True  # only  bool valu 
jsone.toJson()
2

什么是 self.MainFrameDict['currentItemInfo']['description'] 的类型?

它不是 str(字符串)、int(整数)、float(浮点数)、list(列表)、tuple(元组)、bool(布尔值)或 None(空值),所以 json 不知道该怎么处理它。你需要把它转换成这些类型中的一种……

撰写回答