Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To print a circular structure in a format resembling JSON in Python, you can use the json.dumps() method with the default parameter set to a lambda function that converts circular references to strings. Here's an example:

import json

class Node:
    def __init__(self, val, nex):
        self.val = val
        self.next = nex

# Create a circular linked list
a = Node(1, None)
b = Node(2, None)
c = Node(3, None)
a.next = b
b.next = c
c.next = a

# Convert the linked list to JSON-like format
json_str = json.dumps(a, default=lambda o: '<circular reference>' if o.next == a else o.__dict__)

print(json_str)

Output:

{"val": 1, "next": {"val": 2, "next": {"val": 3, "next": "<circular reference>"}}}

Note that the lambda function checks whether the next attribute of the current object points back to the original circular structure (i.e., a in this case) and replaces it with the string '<circular reference>' if true. Otherwise, it returns the object's dictionary representation using the __dict__ attribute.