Try
let t = decode (BS.pack src) :: Maybe [Test]
سؤال
begginners question in haskell, when trying to process JSON data.
I've got a simple file named kk with the following contents:
{
"id": 123,
"name": "Test1"
}
And I am successfully reading and parsing it with the following code:
{-# 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
However, I cannot seem to determine how should I process the file if it is an array, meaning:
[{
"id": 1,
"name": "Test1"
},
{
"id": 2,
"name": "Test2"
}]
How can I fold or otherwise iterate the array case?
المحلول
Try
let t = decode (BS.pack src) :: Maybe [Test]