How to serialize this tree like data structure?

This is my data structure:

struct Tree {
    root: Box<str>,
    branches: Vec<Tree>,
}

I want the output from serde json like this:


{
    root: { 
        another_root: {
            third_root: final_root // if branches are empty(end condition)
        }
}

However my problem is I can't implement serialize trait for this.
It feels like I have to convert my data structure to reflect the data. But, I can't change the data structure now.
In my case, Tree.root will always have unique value. So, duplicate keys will not be an issue.
How to implement this?

You can use the from and into serde attributes to specify an intermediate type to use for serializing and deserializing.

1 Like

I'm not sure your encoding scheme works. How do you expect a node that contains multiple leaves to be encoded, for example? If I understand your intention correctly, this should encode as a JSON object with one key, one, with a value of both two and three at the same time, because they're leaf nodes.

Tree {
    root: "one",
    branches: [
        Tree { root: "two", branches: [] },
        Tree { root: "three", branches: [] },
    ]
}

The closest I could figure out quickly produces something like this:

{
  "one": {
    "two-a": {
      "three": {
        "four": {}
      }
    },
    "two-b": {}
  }
}
2 Likes

Actually, the data structure is a little flawed :sweat_smile:. I have to model the data structure correctly for my use-case. Anyway thanks for the answer.