2

我很难尝试解析类似的结构

{"tree": [5, [[1, 4], [2, 3]]]}

变成二叉树

data Tree a = Leaf a | Node (Tree a) (Tree a)

但我什至似乎无法正确输入类型。这个问题有简单的解决方案吗?

我假设每个 JSON 数组正好包含两个元素,所以结果应该是

Node (Leaf 5) (Node (Node (Leaf 1) (Leaf 4)) (Node (Leaf 2) (Leaf 3))) :: Tree Int

编辑:我尝试过的:

我尝试添加用于导入的新数据类型

data IntTree = IntTree { jsonTree :: Tree Int }

instance FromJSON IntTree
  where
    parseJSON (Object v) = do
        inttree <- (v .: "tree")
        -- now I am stuck
4

1 回答 1

1

当我开始使用 Aeson 时,我发现FromJSONandToJSON类型很有用,但并没有真正理解它们是如何工作的。我发现弄乱Aeson 用来表示 JSON 值的底层类型是很有教育意义的。例如,它HashMap用于对象和Vector数组:

{-# LANGUAGE OverloadedStrings #-}

import Data.Aeson
import qualified Data.HashMap.Strict as H
import qualified Data.Vector as V

j = "{\"tree\": [5, [[1, 4], [2, 3]]]}"

data Tree a = Leaf a | Node (Tree a) (Tree a) deriving (Show)

Just (Object decoded) = decode j :: Maybe Value

Just tree = H.lookup "tree" decoded

parse :: FromJSON a => Value -> Tree a
parse t = case t of
    Array v -> if V.length v /= 2
                   then error "Not a binary tree"
                   else Node (parse (V.head v)) (parse (V.last v))
    x       -> Leaf $ case fromJSON x of
                   Success a   -> a
                   Error   msg -> error msg


main = print $ show $ (parse tree :: Tree Int)
于 2014-09-11T15:31:31.780 回答