How can I serialise test
below:
class Foo:
a = 0
b = {}
def __init__(self, a, b=None):
self.a = a
if b:
self.b = b
test = Foo(1)
test.b['c'] = 2
so that the output is:
{"a": 1, "b": {"c": 2}}
I've tried:
print(json.dumps(test, default=lambda x: x.__dict__))
but it returns:
{"a": 1}
I understand that test.b['c'] = 2
does not add b
or c
to Foo.__dict__
, which is probably why x.__dict__
in the lambda doesn't pick them up. So is the answer one of:
setattr
instead.dict
instead.The problem here is test.b
is not a instance variable. So when you serialize the object test
using json.dumps
, its not finding an instance variable b
at all.
If you redefine the constructor like below:
class Foo:
a = 0 #this is not instance variable - this is a class variable
b = {} #this is not instance variable - this is a class variable
def __init__(self, a, b=None):
self.a = a
self.b = {} #declared the instance variable b also
if b:
self.b = b
test = Foo(1)
test.b['c'] = 2
Now, if you run you get the desired output.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.