B4J Question Tree Structure to Json

Mashiane

Expert
Licensed User
Longtime User
Ola

I need some help..

Lets say we have this tree structure saved as a b4x list

B4X:
a
a\anele.txt
a\b
a\b\c\projects.txt
a\b\c\d\e
b\a\c\anele.txt

how do I make this to have this json structure

B4X:
[
{id=1, name="a", parentid=0}, 
{id=2, name="anele.txt", parentid=1},
{id=3, name="b", parentid=1}, 
{id=4, name="c", parentid=3},
{id=5, name="projects.txt", parentid=4}
{id=6,name="d", parentid=4},
{id=7,name="e", parentid=6},
{id=8,name="b", parentid=0},
{id=9,name="a", parentid=8},
{id=10,name="c",parentid=9},
{id=11,name="anele.txt",parentid=10}
]

Thanks
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Full example except of converting to json, which should be trivial:
B4X:
'non-ui project
Sub Process_Globals
    Type TreeNode (Value As String, Id As Int, Children As List, Parent As TreeNode)
    Private IdCounter As Int
End Sub

Sub AppStart (Args() As String)
    Dim Root As TreeNode = CreateTreeNode("", 0, Null)
    Dim s As String = $"a
a\anele.txt
a\b
a\b\c\projects.txt
a\b\c\d\e
b\a\c\anele.txt"$
    For Each line As String In Regex.Split("\n", s)
        Dim parts() As String = Regex.Split("\\", line)
        WalkTree(Root, parts, 0)
    Next
    PrintTree(Root)    
End Sub

Sub WalkTree (Parent As TreeNode, ItemParts() As String, Index As Int)
    Dim Part As String = ItemParts(Index)
    For Each tn As TreeNode In Parent.Children
        If tn.Value = Part Then
            WalkTree(tn, ItemParts, Index + 1)
            Return
        End If
    Next
    IdCounter = IdCounter + 1
    Dim NewNode As TreeNode = CreateTreeNode(Part, IdCounter, Parent)
    Parent.Children.Add(NewNode)
    If Index < ItemParts.Length - 1 Then
        WalkTree(NewNode, ItemParts, Index + 1)
    End If
End Sub

Sub PrintTree (TN As TreeNode)
    If TN.Parent.IsInitialized = True Then
        Log($"Id: ${TN.Id}, Value: ${TN.Value}, Parent Id: ${TN.Parent.Id}"$)
    End If
    For Each child As TreeNode In TN.Children
        PrintTree(child)
    Next
End Sub

Public Sub CreateTreeNode (Value As String, Id As Int, Parent As TreeNode) As TreeNode
    Dim t1 As TreeNode
    t1.Initialize
    t1.Value = Value
    t1.Id = Id
    t1.Children.Initialize
    If Parent <> Null Then t1.Parent = Parent
    Return t1
End Sub
 
Upvote 0
Top