Programmatically create json hierarchy

To pythonians.
This is the hardest for me - cause it involve recursive

Consider the navigation tree (perspective tree component):
image

How do I build this programmatically, given a table from database:
image

(is the table structured even right?)
In other words, how do I programmatically walk thru the table above to create the code below.

[
  {
    "label": "Main",
    "items": [
      {
        "label": "Prod A",
        "items": [
          {
            "label": "Line 1",
            "items": []
          },
          {
            "label": "Line 2",
            "items": []
          }
        ]
      },
      {
        "label": "Prod B",
        "items": [
          {
            "label": "Line 3",
            "expanded": false,
            "items": []
          },
          {
            "label": "Line 4",
            "items": []
          }
        ]
      }
    ]
  }
]

I started with the below function:

	def getItems(<some query here>):
		itemObj={}
		itemObj['label'] = 'USA'
		itemObj['items'] = []
		return itemObj

I can't think how to start my for loop

@Matthew.gaitan helped me solve a similar problem. In my application I used a Tree component as a navigation tree. The tree was populated by a text file very similar to the database data you've shown there. It worked out really well and the text file made editing the site menu a very simple task using a text field within the application (with appropriate user rights). I documented my final code so I hope it will be of use to you.

4 Likes

Hi Transistor, thank you for this, no doubt this is the solution,
but I do not follow on:

  • Create a source of the menu structure in text.
  • Create an Expression Binding on the Tree's props.items to your text.

It is blur for me,
How do you put the "structured text" on the expression field on the binding?

Sorry, bedtime in Ireland. I'll look at it tomorrow.

I got it.

I literally, copied the code below.
The input is a column from dataset with `completePath'.
Work like a charm.
Thank you for replying to my post quick.