I have the following JSON data in a documentdb and I would like to parse this into an F# multiway tree discriminated union
"commentTree": {
"commentModel": {
"commentId": "",
"userId": "",
"message": ""
},
"forest": []
}
F# multiway discriminated union
type public CommentMultiTreeDatabaseModel =
| CommentDatabaseModelNode of CommentDatabaseModel * list<CommentMultiTreeDatabaseModel>
where CommentMultiTreeDatabaseModel is defined as
type public CommentDatabaseModel =
{ commentId : string
userId : string
message : string
}
I am referencing Fold / Recursion over Multiway Tree in f# extensively. I am not sure where to begin to parse such a JSON structure into an F# multiway tree. Any suggestions will be much appreciated. Thanks
One way to think about this is by looking at what data you need in order to construct a
CommentMultiTreeDatabaseModel
. It needs aCommentDatabaseModel
and a list ofCommentMultiTreeDatabaseModel
. So we need to write the following two functions:But wait, the
parseTree
function is the one we're trying to write right now! So instead of writing a new function, we just mark our current function with therec
keyword and have it call itself where needed.Below is a rough example of how it could be done. The key thing to look at is
parseTree
which builds up the data by recursively calling itself. I've represented the JSON input data with a simple DU. A library like Chiron can produce something like this.Note that this code parses all of the JSON in one go. Also, it's not tail-recursive, so you'll have to be careful with how deep your tree structure is.