Python属性类的JSON序列化

6

我有一个 Properties 类:

from child_props import ChildProps

class ParentProps(object):
    """Contains all the attributes for CreateOrderRequest"""

    def __init__(self):
        self.__prop1 = None            
        self.__child_props = ChildProps()            

    @property
    def prop1(self):
        return self.__prop1

    @prop1.setter
    def prop1(self, value):
        self.__prop1 = value

    @property
    def child_props(self):
        return self.__child_props

    @child_props.setter
        def child_props(self, value):
        self.__child_props = value

另一个类是:

class ChildProps(object):
    """Contains all the attributes for CreateOrderRequest"""

    def __init__(self):
        self.__child_prop1 = None        
        self.__child_prop2 = None


    @property
    def child_prop1(self):
        return self.__child_prop1

    @child_prop1.setter
    def child_prop1(self, value):
        self.__child_prop1 = value

    @property
    def child_prop2(self):
        return self.__child_prop2

    @child_prop2.setter
    def child_prop2(self, value):
        self.__child_prop2 = value

在main.py文件中。
parent_props = ParentProps()
parent_props.prop1 = "Mark"
child_props =  ChildProps()
child_props.child_prop1 = 'foo'
child_props.child_prop2 = 'bar'
parent_props.child_props = child_props

如何将parent_props序列化为以下json字符串:
{
    "prop1" : "Mark",
    "child_props" : {
                        "child_prop1" : "foo",
                        "child_prop2" : "bar"
                    }
}    

PS: json.dumps只能序列化本地的Python数据类型。pickle模块只对对象进行字节级别的序列化。

就像在dotnet中我们有NewtonSoft,在Java中有jackson一样,Python中用于序列化getter/setter属性类对象的等效序列化程序是什么。

我在Google上搜索了很多,但没有得到太多帮助。任何线索将不胜感激。谢谢


2
最简单的方法是编写一个生成该字典的函数,然后json.dumps该字典。 - abarnert
有很多第三方库可以帮助序列化为JSON,甚至以声明性的方式生成类,构建@property__init__和JSON序列化,但SO不是询问库推荐的好地方。如果这是你想要的,而且你在搜索中找不到它,请尝试访问python.org网站上的社区部分(可能是python-list邮件列表或#python IRC频道)。 - abarnert
感谢abarnet的回复。我们可以编写单独的序列化器来执行JSON序列化,但是与其他编程语言一样,我们有一个流行的序列化器来执行该任务,而无需为每个属性类编写单独的序列化器。我正在寻找那个序列化器。我已经检查了python.org网站和IRC频道,但没有得到太多帮助,所以在这里发布了。我希望你明白我的意思。 - Ankur
抱歉,如果您正在寻求图书馆推荐,SO无法为您提供帮助。请查看[帮助]页面获取更多信息。 - abarnert
1个回答

1

Check this:

def serializable_attrs(self):
    return (dict(
        (i.replace(self.__class__.__name__, '').lstrip("_"), value)
        for i, value in self.__dict__.items()
    ))

它应该返回一个包含你的类属性的字典。
我替换了类名,因为在__dict__中的属性看起来像这样:_ChildProps___child_prop1。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接