How to Create a Parent-Child JSON Tree in Python?

Estimated read time 2 min read

To create a parent-child JSON tree in Python, you can use a combination of dictionaries and lists to represent the tree structure. Here’s an example:

# Define sample data for the parent-child tree
data = [
    {"id": 1, "name": "Parent1", "children": [
        {"id": 2, "name": "Child1.1", "children": []},
        {"id": 3, "name": "Child1.2", "children": [
            {"id": 4, "name": "Grandchild1.2.1", "children": []}
        ]}
    ]},
    {"id": 5, "name": "Parent2", "children": [
        {"id": 6, "name": "Child2.1", "children": [
            {"id": 7, "name": "Grandchild2.1.1", "children": []}
        ]}
    ]}
]

# Function to recursively create the parent-child JSON tree
def create_tree(data, parent_id=None):
    children = []
    for item in data:
        if item.get("id") == parent_id:
            children.append(item)
            item["children"] = create_tree(data, item["id"])
    return children

# Create the parent-child JSON tree
json_tree = create_tree(data)

# Print the resulting JSON tree
import json
print(json.dumps(json_tree, indent=4))

In this example, the data variable represents the sample data for the parent-child tree. The create_tree() function is a recursive function that takes in the data and an optional parent ID, and recursively creates the parent-child tree structure using dictionaries and lists. The resulting JSON tree is printed using the json.dumps() method with an indentation of 4 for better readability.

Note that the children key is used to represent the child nodes of each parent node in the JSON tree. The function recursively calls itself to create the child nodes under each parent node, and the children key is added to each parent node as a list of its child nodes. You can modify the function to suit your specific requirements, such as adding additional attributes or customizing the JSON structure as needed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply