Answer the question
In order to leave comments, you need to log in
How to find looped references during serialization and make it possible to deserialize objects back?
Hello!
I came across a seemingly simple, but still incomprehensible puzzle for me. You need to pack various objects into a json and unpack them back on the other side when deserializing. Usually simple objects or classes are sent and this is not a problem at all, but objects with looped references to each other began to appear, for example
class Foo:
def __init__(self):
self.arg = None
class Bar:
def __init__(self):
self.baz = None
foo = Foo()
bar = Bar()
foo.arg = bar
bar.baz = foo
import json
class CircRefEncoder(json.JSONEncoder):
def __init__(self, *args, **argv):
super().__init__(*args, **argv)
self.proc_ids_map = {}
def default(self, obj):
if isinstance(obj, (Foo, Bar)):
object_id = id(obj)
if object_id in self.proc_ids_map:
return {"pyref": object_id} # short circle the object dumping
self.proc_ids_map[object_id] = obj
return {"$object_id": object_id, **obj.__dict__}
return obj
print(json.dumps(foo, cls=CircRefEncoder, check_circular=False))
Answer the question
In order to leave comments, you need to log in
when exporting, you replace links with identifiers,
you export everything as a flat list
, when you import, after creating objects, you restore links from identifiers
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question