[Python] How can I get a list of all nested keys from JSON?

Discussão em 'Python' iniciado por Stack, Agosto 11, 2025.

  1. Stack

    Stack Membro Participativo

    My JSON:

    {
    "Name1": {
    "NNum": "11",
    "Node1": {
    "SubNodeA": "Thomas",
    "SubNodeB": "27"
    },
    "Node2": {
    "SubNodeA": "ZZZ",
    "SubNodeD": "XXX",
    "SubNodeE": "yy"
    },
    "Node3": {
    "child1": 11,
    "child2": {
    "grandchild": {
    "greatgrandchild1": "Rita",
    "greatgrandchild2": "US"
    }
    }
    }
    }
    }


    The format or keys are not defined and can go to any depth. I want a list of keys:

    keyList= ["Name1.NNum","Name1.Node1.SubNodeA",""Name1.Node1.SubNodeB","Name1.Node2.SubNodeA","Name1.Node2.SubNodeD","Name1.Node2.SubNodeE","Name1.Node3.child1","Name1.Node3.child2.grandchild.greatgrandchild1","Name1.Node3.child2.grandchild.greatgrandchild2"]


    My code:

    def extract_values(obj):
    """Pull all values of specified key from nested JSON."""
    arr = []
    key_list = []
    parent = ""
    def extract(obj, arr,parent):
    """Recursively search for values of key in JSON tree."""
    if isinstance(obj, dict):
    grandparent = ""
    for k, v in obj.items():
    print ("k ............",k)
    parent = grandparent
    temp_parent = k
    print ("parent >>>>> ",parent)

    if isinstance(v, (dict, list)):
    parent = temp_parent
    print ("IF VALUE DICT .. parent ", parent)
    extract(v, arr,parent)
    else:
    grandparent = parent
    parent = parent + "_" + temp_parent
    print ("!!!! NOT DICT :).... **** parent ... ", parent)
    arr.append(parent)

    elif isinstance(obj, list):
    for item in obj:
    extract(item, arr)
    #print ("arr >>>>>>>>>> ", arr)
    time.sleep(5)
    return arr

    results = extract(obj, arr,parent)
    return results


    But this does not give the expected output.

    Continue reading...

Compartilhe esta Página