'dict_items'类型的对象不是JSON可序列化的

时间:2018-01-22 04:27:03

标签: python json

如何将dict_item保存到json文件以将其加载到其他位置? 我在浏览器中使用js获取列表并返回到python,但我无法将其保存为Json文件,因为它说:

  

'dict_items'类型的对象不是JSON可序列化的

Javascript提取列表:

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

堆栈跟踪:

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

存储数据的代码:

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

我跑的内容:

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"')])

1 个答案:

答案 0 :(得分:2)

您遇到的问题是:

session_ls = storage.get().items()

为什么.items()?与Python 2不同,在Python 3中,这是一个视图对象。所以我可以看到两种可能的解决方案:

session_ls = storage.get()

这会给你一个字典,可以传递给json.dump()。或者,如果您确实需要session_ls作为项目,可以尝试:

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

或:

json.dump(list(session_ls), fp)