JSON (de) serialization for nested classes

X is a simple class with three fields:

 class X(): def __init__(self, a, b, c): self.a = a self.b = b self.c = c 

JSON Encoder / Decoder for X :

 class XEncoder(json.JSONEncoder): def encode(self, obj): return super(XEncoder, self).encode({ 'a': obj.a, 'b': obj.b, 'c': obj.c }) class XDecoder(json.JSONDecoder): def decode(self, json_string): obj = super(XDecoder, self).decode(json_string) return X(obj['a'], obj['b'], obj['c']) 

Y , which has X as the dict value inside the field:

 class Y(): def __init__(self): self.m = {} def add(self, a, x): self.m[a] = x 

What will the JSON encoder / decoder for Y look like?

+4
source share
1 answer
 class YEncoder(json.JSONEncoder): def encode(self, obj): return json.dumps({ 'm': json.dumps({ k: json.dumps(v, cls=XEncoder) for k, v in obj.m.items()})}) class YDecoder(json.JSONDecoder): def decode(self, json_string): ym = {k: json.loads(v, cls=XDecoder) for k, v in json.loads(json.loads(json_string)['m']).items()} return y 
+1
source

Source: https://habr.com/ru/post/1493236/


All Articles