Python Properties 类的 Json 序列化

Ank*_*kur 5 python serialization json python-2.7 json-serialization

我有一个属性类:

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
Run Code Online (Sandbox Code Playgroud)

另一个类是:

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
Run Code Online (Sandbox Code Playgroud)

在 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
Run Code Online (Sandbox Code Playgroud)

如何将 parent_props 序列化为 json 字符串,如下所示:

{
    "prop1" : "Mark",
    "child_props" : {
                        "child_prop1" : "foo",
                        "child_prop2" : "bar"
                    }
}    
Run Code Online (Sandbox Code Playgroud)

PS : json.dumps 只能序列化原生 python 数据类型。pickle 模块只将对象序列化为字节。

就像我们在 dotnet 中有 NewtonSoft,在 java 中有 jackson 一样,Python 中的等效序列化器是什么来序列化 getter setter 属性类对象。

我在谷歌搜索了很多,但没有得到太多帮助。任何领先都将是可观的。谢谢

小智 1

检查一下:

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

它应该返回一个包含您的类属性的字典。

我替换了类名,因为其中的属性__dict__如下所示:_ChildProps___child_prop1