I have data like this which represents hierarchical tree structure:
[
{
"level":0,
"name":"python"
},
{
"level":1,
"name":"food"
},
{
"level":2,
"name":"banana"
},
{
"level":3,
"name":"protein"
},
{
"level":2,
"name":"apple"
},
{
"level":1,
"name":"fuel"
}
]
I want to transform it into:
[
{
"level":0,
"name":"python",
"children":[
{
"level":1,
"name":"food",
"children":[
{
"level":2,
"name":"banana",
"children":[
{
"level":3,
"name":"protein",
"children":[
]
}
]
},
{
"level":2,
"name":"apple",
"children":[
]
}
]
},
{
"level":1,
"name":"fuel",
"children":[
]
}
]
}
]
I am using python and would prefer the solution in python with or without using external libraries, (even using pandas). I would love to see the solutions, thank you in advance 🙂
2
Answers
Here is one way:
which gives what you wanted
I suppose the order of the dictionaries in your list matters, since otherwise I wouldn’t know under which parent the children are supposed to be listed. I would suggest to write a recursive function to get the last element at level n and append the children there:
Output: