[英]How to serialise both positional and non-positional arguments of Python objects?
How can I serialise test
below:我如何在下面序列化
test
:
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.我知道
test.b['c'] = 2
不会将b
或c
添加到Foo.__dict__
,这可能就是为什么 lambda 中的x.__dict__
没有选择它们的原因。 So is the answer one of:答案之一是:
setattr
instead.setattr
。dict
instead.dict
。The problem here is test.b
is not a instance variable.这里的问题是
test.b
不是实例变量。 So when you serialize the object test
using json.dumps
, its not finding an instance variable b
at all.因此,当您使用
json.dumps
序列化对象test
,它根本找不到实例变量b
。
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.现在,如果您运行,您将获得所需的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.