Ask Your Question
1

What is the method to print a circular structure in a format resembling JSON?

asked 2022-11-05 11:00:00 +0000

david gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-09-02 17:00:00 +0000

plato gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-11-05 11:00:00 +0000

Seen: 15 times

Last updated: Sep 02 '22