0

Within the following class I am trying to save some state information to a json file, however when I attempt to save a dictionary I come across a 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)

Within the dictionary that I am trying to save:

(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'>

The traceback that I am trying to figure out:

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

Docs/Posts looked at:

I am not sure if this is because it is nested, or if there is an issue with encoding/decoding. What exactly am I looking for and what am I not understanding? Is there a way to determine the encoding of an item?

martineau
  • 119,623
  • 25
  • 170
  • 301
jmunsch
  • 22,771
  • 11
  • 93
  • 114
  • 2
    what is the _type_ of `(self.MainFrameDict['currentItemInfo']['description'])`? It's not a string, int, float, list, tuple, boolean or None, so json doesn't know what to do with it. You'll need to convert it to one of those types... – mgilson Apr 11 '14 at 17:17
  • Oh dang! `` I didn't even. I'll just work on that. Thanks! – jmunsch Apr 11 '14 at 17:21
  • Perfect! If you move your comment to an answer, that solved it. So much to learn. Thanks. – jmunsch Apr 11 '14 at 17:28

2 Answers2

2

what is the type of self.MainFrameDict['currentItemInfo']['description']?

It's not a str, int, float, list, tuple, bool or None, so json doesn't know what to do with it. You'll need to convert it to one of those types...

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • I had an error with the Mandrill API when passing a file argument to it. With this answer, I wrapped the read() file in str(html_file), and it fixed this error. Thnx – Aaron Lelevier Dec 04 '14 at 23:44
0

You can try this. In case of me its work 100%. And can rncode into json any kind of python objects like dictionary, list, tuple etc or normal class object.

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

At last call the Utility class like that .and convert to json

jsone = Utility()
jsone.result=result # any kind of object
json.error=True  # only  bool valu 
jsone.toJson()
Stefan Becker
  • 5,695
  • 9
  • 20
  • 30