简体   繁体   中英

Loop through a nested dictionary and get its path

I have a JSON object with the following structure:

source = {
"org_name": "root",
"orgs": [
    {
        "org_name": "alpha1",
        "orgs": []
    },
    {
        "org_name": "alpha2",
        "orgs": [
            {
                "org_name": "beta1",
                "orgs": [
                    {
                        "org_name": "gama1",
                        "orgs": []
                    }
                ]
            }
        ]
    }
]

}

I want to parse this JSON and add a key named org_path which contains the path of the orgs the output should be like this

source = {
"org_name": "root",
"org_path": "root"
"orgs": [
    {
        "org_name": "alpha1",
        "org_path": "root/alpha1"
        "orgs": []
    },
    {
        "org_name": "alpha2",
        "org_path": "root/alpha2"
        "orgs": [
            {
                "org_name": "beta1",
                "org_path": "root/alpha2/beta1"
                "orgs": [
                    {
                        "org_name": "gama1",
                        "org_path": "root/alpha2/gama1"
                        "orgs": []
                    }
                ]
            }
        ]
    }
]
}

I am having a hard time finding a logic to get a output.

Here is a solution

def add_path_to_dict(dictionary, path=""):
    path += dictionary["org_name"]
    dictionary["org_path"] = path
    path +="/"
    for orgs in dictionary["orgs"]:
        orgs = add_path_to_dict(orgs, path)
    return dictionary


if __name__ == "__main__":
    print(add_path_to_dict(source))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM