What would be the pythonic way to go to prevent circular loop while writing JSON?

What would be the pythonic way to go to prevent circular loop while writing JSON?

I have&nbsp;<strong>two classes A and B, each one storing references to objects of the other class</strong>&nbsp;in lists:

I have two classes A and B, each one storing references to objects of the other class in lists:

class A:
    def __init__(self,name):
        self.name = name
        self.my_Bs = []
    def registerB(self,b):
        self.my_Bs.append(b)

class B: def init(self,name): self.name = name self.my_As = [] def registerA(self,a): self.my_As.append(a)

Now, my app builds two lists, one of objects of A, one of objects of B, having cross references.

# a list of As, a list of Bs
list_of_As = [A('firstA'), A('secondA')]
list_of_Bs = [B('firstB'), B('secondB')]

example of one cross-reference

list_of_As[0].registerB(list_of_Bs[1]) list_of_Bs[1].registerA(list_of_As[0])

Obviously, if I call json.dumps() on either list_of_..., I get a circular reference error.

What I want to do to circumvent that issue is to dump JSON with list of elements name attributesinstead of lists of objects themselves:

# This is what I want to obtain for

the JSON for list_of_As

[ {'name' : 'firstA', 'my_Bs': ['secondB']}, {'name' : 'secondA', 'my_Bs': []} ]

The only way I can think of is to maintain in each class an additional list of strings (respectively my_Bs_names and my_As_names) and to use JSONEncoder as follows:

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, 'A'):
            return { # filter out the list of B objects
                k: v for k, v in obj.dict.items() if k != 'my_Bs'
            }
        if isinstance(obj, 'B'):
            return { # filter out the list of A objects
                k: v for k, v in obj.dict.items() if k != 'my_As'
            }
        return super(MyEncoder, self).default(obj)

Use the custom encoder to dump JSON for list_of_As

print json.dumps(list_of_As, cls=MyEncoder)

If I am not mistaken, I would get the following result:

# This is what I obtain for

the JSON for list_of_As with the code above

[ {'name' : 'firstA', 'my_Bs_names': ['secondB']}, {'name' : 'secondA', 'my_Bs_names': []} ]

Is there a more elegant way of getting this result? For instance one that does not require any additional lists of strings?

Angular 9 Tutorial: Learn to Build a CRUD Angular App Quickly

What's new in Bootstrap 5 and when Bootstrap 5 release date?

Brave, Chrome, Firefox, Opera or Edge: Which is Better and Faster?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Python Tutorial: Working with JSON Data using the json Module

In this Python Programming Tutorial, we will be learning how to work with JSON data. We will learn how to load JSON into Python objects from strings and how to convert Python objects into JSON strings. We will also see how to load JSON from a file and save those Python objects back to files

Python Script 3: Validate, format and Beautify JSON string Using Python

Python Script 3:Validate, format and Beautify JSON string Using Python - As per official JSON website, JSON is a light-weight data interchange format. It is easy for humans to read and write.It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language

Top Python Development Companies | Hire Python Developers

After analyzing clients and market requirements, TopDevelopers has come up with the list of the best Python service providers. These top-rated Python developers are widely appreciated for their professionalism in handling diverse projects. When...