Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create JSON from Python classes with inheritence

I'm attempting to recreate the following JSON using python classes with inheritence :

{"attribute1": "c1"
"attribute2": {"attribute3" : "test"}
}

So far I have this code:

class class1():
    def __init__(self, attribute1):
        self.attribute1 = attribute1

class class2(class1):
    def __init__(self, attribute2):
        class1.__init__(self, 'test')
        self.attribute2 = attribute2

c1 = class1('c1')
c2 = class2(c1)

print(json.dumps(c1.__dict__))

renders:

{"attribute1": "c1"}

If I try to convert the variable c2 to JSON:

print(json.dumps(c2.__dict__))

I receive error:

TypeError: Object of type class1 is not JSON serializable

Shouldn't class1 be serializable as I convert it previously using print(json.dumps(c1.__dict__))

like image 961
blue-sky Avatar asked Apr 29 '26 10:04

blue-sky


1 Answers

Shouldn't class1 be serializable as I convert it previously using print(json.dumps(c1.dict))

That isn't how JSON works. It expects to find a dictionary at each level. When you run, json.dumps(c2.__dict__) you've helped it find the dictionary for c2' but you haven't told it how to find the dict for c1. It won't remember your previous call to json.dumps(c1.__dict__)

I'm attempting to recreate the following JSON using python classes with inheritance

This likely won't work out cleanly. Nested JSON models HAS-A relationships while inheritance models IS-A relationships.

like image 159
Raymond Hettinger Avatar answered May 01 '26 00:05

Raymond Hettinger



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!