Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object of type 'dict_items' is not JSON serializable

Tags:

python

json

How could I save a dict_item to a json file to load it in another place? I am getting the list with js in my browser and returning into python, but I cannot save it as a Json file because it says:

Object of type 'dict_items' is not JSON serializable

Javascript to extract the list:

var items = {}, ls = window.localStorage;
for (var i = 0, k; i < ls.length; i++)
   items[k = ls.key(i)] = ls.getItem(k);
return items;

Stacktrace:

Traceback (most recent call last):
  File "tester.py", line 9, in <module>
    obj.store()
  File "F:\project\zw\zwp.py", line 69, in store
    json.dump(session_ls, fp)
  File "c:\users\dkun\appdata\local\programs\python\python36\Lib\json\__init__.py", line 179, in dump
    for chunk in iterable:
  File "c:\users\dkun\appdata\local\programs\python\python36\Lib\json\encoder.py", line 437, in _iterencode
    o = _default(o)
  File "c:\users\dkun\appdata\local\programs\python\python36\Lib\json\encoder.py", line 180, in default
    o.__class__.__name__)
TypeError: Object of type 'dict_items' is not JSON serializable

Code to store the data:

storage = LocalStorage(self.driver)
session_ls = storage.get().items()
with open('../assets/tmp/session.json', 'w') as fp:
    json.dump(session_ls, fp)

Content if I run:

print(repr(session_ls))

dict_items([('Dexie.DatabaseNames', '["wawc"]'), ('Gds7Zz7akA==', 'false'), ('BrowserId', '"A=="'), ('LangPref', '"en"'), ('SecretBundle', '{"key":"X=","encKey":"X","macKey":"X="}'), ('Token1', '"Y="'), ('Token2', '"1=="'), ('Y==', 'false'), ('debugCursor', '263'), ('l==', '[{"id":"global_mute","expiration":0}]'), ('logout-token', '"1=="'), , ('remember-me', 'true'), ('storage_test', 'storage_test'), ('==', 'false'), ('mutex', '"x19483229:init_15"')])
like image 443
davis Avatar asked Jan 28 '23 19:01

davis


1 Answers

The problem you are having is here:

session_ls = storage.get().items()

Why .items()? Unlike in Python 2, in Python 3, this is a view object. So two possible solutions I can see:

session_ls = storage.get()

This will give you a dict, which can be passed to json.dump(). Or, if you really need session_ls to be items, you might try:

session_ls = list(storage.get().items())

or:

json.dump(list(session_ls), fp)
like image 138
Stephen Rauch Avatar answered Jan 31 '23 20:01

Stephen Rauch