在haskell中的begginners问题。
我有一个名为 kk 的简单文件,其中包含以下内容:
{
"id": 123,
"name": "Test1"
}
我使用以下代码成功阅读并解析它:
{-# LANGUAGE OverloadedStrings #-}
import Data.Aeson
import Data.Aeson.Types
import Control.Applicative ((<$>), (<*>))
import Control.Monad
import qualified Data.ByteString.Lazy.Char8 as BS
data Test = Test { id ∷ Integer
, name ∷ String
} deriving (Show)
process v = Test <$>
(v .: "id") <*>
(v .: "name")
instance FromJSON Test where
parseJSON (Object o) = process o
parseJSON (Array a) = mzero
parseJSON _ = mzero
main = do
src ← readFile "kk"
let t = decode (BS.pack src) ∷ Maybe Test
print t
但是,我似乎无法确定如果它是一个数组我应该如何处理该文件,这意味着:
[{
"id": 1,
"name": "Test1"
},
{
"id": 2,
"name": "Test2"
}]
如何折叠或以其他方式迭代数组大小写?
答案 0 :(得分:4)
尝试
let t = decode (BS.pack src) :: Maybe [Test]