我希望序列化包含嵌套列表的python列表。下面的代码从gnome密钥环构造要序列化的对象,但是jsonpickle编码器,不会将子列表序列化。使用unpicklable=True
,我只需:
[{"py/object": "__main__.Collection", "label": ""}, {"py/object": "__main__.Collection", "label": "Login"}]
我已尝试设置/不设置max_depth
并尝试了很多深度数字,但无论如何,选择器只会挑选顶级项目。
如何使其序列化整个对象结构?
#! /usr/bin/env python
import secretstorage
import jsonpickle
class Secret(object):
label = ""
username = ""
password = ""
def __init__(self, secret):
self.label = secret.get_label()
self.password = '%s' % secret.get_secret()
attributes = secret.get_attributes()
if attributes and 'username_value' in attributes:
self.username = '%s' % attributes['username_value']
class Collection(object):
label = ""
secrets = []
def __init__(self, collection):
self.label = collection.get_label()
for secret in collection.get_all_items():
self.secrets.append(Secret(secret))
def keyring_to_json():
collections = []
bus = secretstorage.dbus_init()
for collection in secretstorage.get_all_collections(bus):
collections.append(Collection(collection))
pickle = jsonpickle.encode(collections, unpicklable=False);
print(pickle)
if __name__ == '__main__':
keyring_to_json()
答案 0 :(得分:2)
我遇到了同样的问题,并且能够通过在init中移动数组声明来解决它:
class Collection(object):
label = ""
# secrets = [] (move this into __init__)
def __init__(self, collection):
self.secrets = []
self.label = collection.get_label()
for secret in collection.get_all_items():
self.secrets.append(Secret(secret))