代码之家  ›  专栏  ›  技术社区  ›  lsund

用Haskell-Aeson解析Json玫瑰树

  •  0
  • lsund  · 技术社区  · 6 年前

    我试图解析递归的JSON数据,类似这样:

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

    现在我想实现一个FromJSON实例,这样我就可以把它解码成这样的数据结构: 以下数据结构

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

    我不知道怎么做。我只看到了如何使用Aeson为平面(非递归)JSON结构派生实例的示例。

    1 回复  |  直到 6 年前
        1
  •  0
  •   lsund    6 年前

    正如Willem von Onsem所建议的,如果您将数据定义为:

    data Tree = Node { value :: Text, children :: [Tree]} ,只是使用空列表来表示(也在json中)空子树。然后,您只需直接通过派生 fromJSON 数据类型的。

    另一个想法是使用 Data.Tree 已具有的派生实例 从JSON

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