-1

I have a json file and its structure is like a nested tree:

{
    "sub": [
    {
        "code": "01",
        "name": "a"
    },
    {
        "code": "02",
        "name": "b",
        "sub": [
        {
            "code": "0201",
            "name": "b1"
        },
        {
            "code": "0202",
            "name": "b2",
            "sub":[{
                "code": "020201",
                "name": "b21"
            },{
                "code": "020202",
                "name": "b22"
            }]
        }]
    },
    {
        "code": "03",
        "name": "c",
        "sub": [
        {
            "code": "0301",
            "name": "c1"
        },
        {
            "code": "0302",
            "name": "c2"
        }]
    }]
}

I want an algorithm to get all sets of leaf node siblings(only name attribute is needed). In the above example should return:

[
 ['a'],
 ['b1'],
 ['b21','b22'],
 ['c1','c2']
]

Note that each element is a leaf node and nodes in each group are siblings.

How can I implement this in python3.x ?

def traverse(tree):
    #how to implement this function?

with open('demo.json') as f:
    tree = json.load(f)
    traverse(tree)
ken wang
  • 165
  • 1
  • 12

1 Answers1

2

You can implement this recursively: Check whether the current tree has sub-nodes, then collect and yield the names of all the sub-nodes that are leafs. Then, just recurse on each sub-node.

def traverse(tree):
    if "sub" in tree:
        yield [sub["name"] for sub in tree["sub"] if "sub" not in sub]
        for sub in tree["sub"]:
            yield from traverse(sub)
tobias_k
  • 81,265
  • 12
  • 120
  • 179