类型'dict_items'的对象不可JSON序列化 [英] Object of type 'dict_items' is not JSON serializable

查看:86
本文介绍了类型'dict_items'的对象不可JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何将dict_item保存到json文件以将其加载到另一个位置? 我正在浏览器中获取带有js的列表,然后返回到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:

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

Object of type 'dict_items' is not JSON serializable

提取列表的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;

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

用于存储数据的代码:

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

推荐答案

您遇到的问题在这里:

session_ls = storage.get().items()

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

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

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

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

或:

json.dump(list(session_ls), fp)

这篇关于类型'dict_items'的对象不可JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆