Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json serialization of Python Properties class

I have a Properties class :

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

And Another class is :

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

In 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

How to serialize parent_props to json string like below :

{
    "prop1" : "Mark",
    "child_props" : {
                        "child_prop1" : "foo",
                        "child_prop2" : "bar"
                    }
}    

PS : json.dumps can only serialize native python datatypes. pickle module only does object serialization to bytes.

Just like we have NewtonSoft in dotnet, jackson in java, what is the equivalent serializer in Python to serialize getter setter properties class object.

I have serached a lot in google but couldn't get much help. Any lead will be much appreciable. Thanks

like image 266
Ankur Avatar asked Nov 08 '22 09:11

Ankur


1 Answers

Check this:

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

It should return a dictionary with properties of your class.

I replaced class name because properties in __dict__ will look like: _ChildProps___child_prop1.

like image 166
Kasikn77 Avatar answered Nov 15 '22 07:11

Kasikn77