如何解析Haskell中的Json对象列表?

时间:2016-04-25 04:00:16

标签: json haskell aeson

我有一个数据类:

data MyData = MyData { a :: Int, b :: String }
instance ToJSON MyData where
  ....

instance FromJSON MyData where
  ....

我可以解析json中的单个对象:

get :: IO (Maybe MyData)
get = do
  res <- getSingleItemHttp
  return $ decode $ responseBody res

如何获取MyData列表?

get2 :: IO [MyData]
get2 = do
      res <- getManyItemsHttp

      --????
      return $ decode $ responseBody res -- doesn't compile

我如何将responseBody解析为List

1 个答案:

答案 0 :(得分:2)

它应该像传入数组一样工作(并作为列表解码),因此您可能只需要将签名更改为get2 :: IO (Maybe [MyData])

{-# LANGUAGE DeriveGeneric, OverloadedStrings #-}
module Json where

import GHC.Generics
import Data.Aeson
import Data.Text
import Data.ByteString.Lazy

data MyData = MyData { a :: Int, b :: String }
  deriving (Generic, Show)

instance FromJSON MyData

example :: ByteString
example = "[{ \"a\": 1, \"b\": \"Hello\" }, { \"a\": 2, \"b\": \"World\" }]"

例如

λ> decode example :: Maybe [MyData]
Just [MyData {a = 1, b = "Hello"},MyData {a = 2, b = "World"}]

你的问题

会是这样的:如果你试试

get :: [MyData]
get = decode example

编译器会抱怨

  

无法将预期类型[MyData]与实际类型Maybe a0 ...

匹配

应该给你一个很大的提示。

您仍可以使用Data.Maybe.maybeToList

获取签名
get :: [MyData]
get = Prelude.concat . maybeToList $ decode example