Saturday, 29 May 2021

How to create a tree using BFS in python?

So I have a flattened tree in JSON like this, as array of objects:

[{
    aid: "id3",
    data: ["id1", "id2"]
},

{
    aid: "id1",
    data: ["id3", "id2"]
},

{
    aid: "id2",
    nested_data: {aid: "id4", atype: "nested", data: ["id1", "id3"]},
    data: []
}]

I want to gather that tree and resolve ids into data with recursion loops into something like this (say we start from "id3"):

{
   "aid":"id3",
   "payload":"1",
   "data":[
      {
         "id1":{
            "aid":"id1",
            "data":[
               {
                  "id3":null
               },
               {
                  "id2":null
               }
            ]
         }
      },
      {
         "id2":{
            "aid":"id2",
            "nested_data":{
               "aid":"id4",
               "atype":"nested",
               "data":[
                  {
                     "id1":null
                  },
                  {
                     "id3":null
                  }
               ]
            },
            "data":[
               
            ]
         }
      }
   ]
}

So that we would get breadth-first search and resolve some field into "value": "object with that field" on first entrance and "value": Null

How to do such a thing in python 3?



from How to create a tree using BFS in python?

No comments:

Post a Comment