Iterate through Json most efficiently using Python

Viewed 36

I want to make sure I am iterating through a Json file most efficiently. Seems I have to many "for" loops. Possibly a better, more expert way, to loop through json with some "if" conditions? The goal is to flatten the json file to a customizes dict.

Example Json:

{
    "Tier1": [
        {
            "Tier2_A": {"id": "11111"},
            "Tier2_B": [],
            "Tier2_C": [
                {
                    "Sub_Tier_C1": {"id": "22222"},
                    "Sub_Tier_C2": [
                        {
                            "Id_1": "78965",
                            "Id_2": "28493",
                        },
                        {
                            "Id_1": "49382",
                            "Id_2": "434234",
                        }
                    ]}

Example Python Code:

store = {}
jsonload = get_json_load()

for Tier1, Tier1_List in jsonload.items():
    store[Tier1] = set()

    for Tier1_Dict in Tier1_List:
        if Tier1_Dict["Tier2_C"]:
            for Tier1_Dict_Dict in Tier1_Dict["Tier2_C"]:
                for Tier1_Dict_Dict_Dict in Tier1_Dict_Dict["Sub_Tier_C2"]:
                    if Tier1_Dict_Dict_Dict == "Id_1":
                        store[Tier1].add((Tier1_Dict["Tier2_A"]["id"], Tier1_Dict_Dict_Dict["Id_1"]))
                    elif Tier1_Dict_Dict_Dict == "Id_2":
                        store[Tier1].add((Tier1_Dict["Tier2_A"]["id"], Tier1_Dict_Dict_Dict["Id_2"]))

return store
1 Answers

Try this

import json

data = json.load("/path/to/file.json")

tier1_tier2_c = {tier1["Tier2_A"]["id"], tier1["Tier2_C"]
                 for key, tier1 in data.items()}

result = { key, set((subtier["Id_1"], subtier["Id_2"])
                    for subtier in tier2_c["Sub_Tier_C2"]) 
           for key, tier2_c in tier1_tier2_c.items()}
Related