Python arbitrary objects Serialization and Deserialization I am trying to convert objects inside an object(arbitrary objects) to Json and later retrieve it. I have developed some codes and would like to share if there is any problem in the code.
import json

Here is the first class
class Foo():
    def __init__(self,x,y,bar):
        self.x =x
        self.y = y
        self.bar = bar #Second class object is here

    def toJson(self):
        return json.dumps(Foo(self.x,self.y,self.bar).__dict__)

    @staticmethod
    def fromJson(jsonData):
        data =  json.loads(jsonData)
        return Foo(
            x = data['x'],
            y = data['y'],
            bar = Bar.fromJson(data['bar'])
        )

Here is the second class
class Bar():
    def __init__(self, z):
        self.z = z


    def toJson(self):
        return json.dumps(Bar(self.z).__dict__)

    @staticmethod
    def fromJson(jsonData):
        data =  json.loads(jsonData)
        return Bar(
            z = data['z'],
        )

Convert to Json
jsonData = Foo(100,500,Bar(900).toJson()).toJson()

Retrieve the Json and convert to Object
foo = Foo.fromJson(jsonData)

Print the Object attributes
print(foo.bar.z)

It works actually. But is there any memory leakage? Any security issue?
There's a library for this dataclasses-json. Whilst it's a pretty poor library the internal code is bad, there's few tests, the documentation is quite small and the design is starting to suffer from these poor decisions. It works, and for your code it is good enough.
You should be able to see that all serialization and deserialization is performed automatically. This is good as then you can focus on using the objects rather than converting to and from them.
from __future__ import annotations

from dataclasses import dataclass

from dataclasses_json import dataclass_json


@dataclass_json
@dataclass
class Foo:
    x: int
    y: int
    bar: Bar


@dataclass_json
@dataclass
class Bar:
    z: int


raw = '{&quot;x&quot;: 100, &quot;y&quot;: 500, &quot;bar&quot;: {&quot;z&quot;: 900}}'
obj = Foo.from_json(raw)
assert obj == Foo(100, 500, Bar(900))
assert obj.to_json() == raw