2013-01-20 34 views
2

begginners問題。如何在試圖處理JSON數據時在haskell中匹配Aeson中的陣列

我有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" 
}] 

我該如何摺疊或以其他方式迭代數組案例?

+2

剛剛送走我的頭頂,你有沒有試過'令t =解碼(BS.pack SRC)∷也許[測試]'? – dave4420

+1

我很確定我必須匹配*數組*,它從來沒有發生過我......就是這樣! Tks – jcristovao

+0

@ dave4420:您也可以將其作爲答案,以便將問題標記爲已解決。 –

回答

4

嘗試

let t = decode (BS.pack src) :: Maybe [Test]