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)