Home > Blockchain >  Python JSON get all children and grandchildren
Python JSON get all children and grandchildren

Time:10-30

My JSON data looks like this:

data = {
    "areas": [
        {
            "id": "1348828088398400836",
            "name": "Building A",
            "children": [
                {
                    "id": "1348828088398403213",
                    "name": "Floor 1",
                    "children": [
                        {"id": "1348828088398403214", "name": "Room 1", "children": []},
                        {"id": "1348828088398403215", "name": "Room 2", "children": []},
                        {"id": "1348828088398403216", "name": "Room 3", "children": []},
                        {
                            "id": "1348828088398403217",
                            "name": "Room 4",
                            "children": [
                                {
                                    "id": "1348828088398407094",
                                    "name": "Washroom",
                                    "children": [],
                                }
                            ],
                        },
                    ],
                }
            ],
        }
    ]
}

Right now I am reading JSON data like this:

for i in data["areas"]:
    areaName = i["name"]
    for j in i["children"]:
        print("Name:", j["name"])
        for k in j["children"]:
            print("Name:", k["name"])
            for l in k["children"]:
                print("Name:", l["name"])

The problem with this approach is that it will miss any children under washroom is there any way to make this dynamic, instead of doing multiple for-loops to get each child?

CodePudding user response:

You can use a recursive function like so:

from typing import Any


data = ...


def print_children(dictionary: dict[str, Any]) -> None:
    print("Name:", dictionary.get("name"))
    if "children" not in dictionary.keys():
        return
    for child_dict in dictionary["children"]:
        print_children(child_dict)


if __name__ == "__main__":
    for area_dict in data["areas"]:
        print_children(area_dict)

Output:

Name: Building A
Name: Floor 1
Name: Room 1
Name: Room 2
Name: Room 3
Name: Room 4
Name: Washroom

CodePudding user response:

https://github.com/hansalemaos/flatten_any_dict_iterable_or_whatsoever

from flatten_any_dict_iterable_or_whatsoever import fla_tu

data = {
    "areas": [
        {
            "id": "1348828088398400836",
            "name": "Building A",
            "children": [
                {
                    "id": "1348828088398403213",
                    "name": "Floor 1",
                    "children": [
                        {"id": "1348828088398403214", "name": "Room 1", "children": []},
                        {"id": "1348828088398403215", "name": "Room 2", "children": []},
                        {"id": "1348828088398403216", "name": "Room 3", "children": []},
                        {
                            "id": "1348828088398403217",
                            "name": "Room 4",
                            "children": [
                                {
                                    "id": "1348828088398407094",
                                    "name": "Washroom",
                                    "children": [],
                                }
                            ],
                        },
                    ],
                }
            ],
        }
    ]
}
for item, keys in list(fla_tu(data)):
    print(f'{item=}', f'{keys=}')
item='1348828088398400836' keys=('areas', 0, 'id')
item='Building A' keys=('areas', 0, 'name')
item='1348828088398403213' keys=('areas', 0, 'children', 0, 'id')
item='Floor 1' keys=('areas', 0, 'children', 0, 'name')
item='1348828088398403214' keys=('areas', 0, 'children', 0, 'children', 0, 'id')
item='Room 1' keys=('areas', 0, 'children', 0, 'children', 0, 'name')
item='1348828088398403215' keys=('areas', 0, 'children', 0, 'children', 1, 'id')
item='Room 2' keys=('areas', 0, 'children', 0, 'children', 1, 'name')
item='1348828088398403216' keys=('areas', 0, 'children', 0, 'children', 2, 'id')
item='Room 3' keys=('areas', 0, 'children', 0, 'children', 2, 'name')
item='1348828088398403217' keys=('areas', 0, 'children', 0, 'children', 3, 'id')
item='Room 4' keys=('areas', 0, 'children', 0, 'children', 3, 'name')
item='1348828088398407094' keys=('areas', 0, 'children', 0, 'children', 3, 'children', 0, 'id')
item='Washroom' keys=('areas', 0, 'children', 0, 'children', 3, 'children', 0, 'name')
  • Related