0
votes

I'm trying to parse recursive JSON data, something like this:

{
    "node": "a",
    "children": [
        {
            "node": "b",
            "children": [
                {
                    "node": "c",
                    "children": null
                }
            ]
        },
        {
            "node": "d",
            "children": null
        }
    ]
}

Now I want to implement an instance of FromJSON, so that I can decode it into a data structure like this: the following data structure

data Tree = Node { value :: Text, children :: [Tree]} | Nothing

I have no clue how to do this. I have only seen examples on how to derive instances for flat (non-recursive) JSON structures using Aeson.

1
The problem here is more the fact that you use null instead of an empty list. Furthermore why do you create a constructor Nothing here? Without the null case, this is actually completely the same as non-flat data.Willem Van Onsem
You are right. It is really simple if you just use empty lists to represent no children!lsund
So... problem solved?Thomas M. DuBuisson
@lsund It should be quite straightforward to define custom FromJSON/ToJSON instances manually. Do you need help with that? (If no, you can also answer your own question, and this is encouraged!)Petr
I answered my own question. Thank you alllsund

1 Answers

0
votes

As Willem von Onsem suggested, this is much simpler if you define the data like this:

data Tree = Node { value :: Text, children :: [Tree]}, just using an empty list for representing (also in the json) empty subtrees. Then, you just parse the json directly by just deriving fromJSON of the datatype.

Another idea is to use Data.Tree which already has a derived instance of fromJSON. For Data.Tree, the JSON has to be structured something like like this:

["a",["b",[]]]