【问题标题】:Serialise child collections in Python (with jsonpickle)在 Python 中序列化子集合(使用 jsonpickle)
【发布时间】:2015-10-25 10:32:07
【问题描述】:

我想序列化一个包含嵌套列表的 python 列表。下面的代码构造了要从 gnome 密钥环序列化的对象,但 jsonpickle 编码器不会序列化子列表。使用unpicklable=True,我得到:

[{"py/object": "__main__.Collection", "label": ""}, {"py/object": "__main__.Collection", "label": "Login"}]

我已经尝试设置/不设置max_depth 并尝试了很多深度数字,但无论如何,pickler 只会腌制顶级项目。

如何让它序列化整个对象结构?

#! /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()

【问题讨论】:

    标签: python json recursion jsonpickle


    【解决方案1】:

    我遇到了同样的问题,并且能够通过在 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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-06
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      相关资源
      最近更新 更多