計算機科学のブログ

実践Haskell Aesonを使ったJSONデータの処理 インスタンス、ToJSON、toJSON関数、(.=)演算子

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT7(実践Haskell)、LESSON 40(Aesonを使ったJSONデータの処理)、40.6(練習問題)Q40-1の解答を求めてみる。

コード

{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics
import Data.Text as T
import Text.Show (Show)
import Data.Aeson

data NOAAResult = NOAAResult { uid :: T.Text 
                             , mindate :: T.Text
                             , maxdate :: T.Text
                             , name :: T.Text
                             , datacoverage :: Double
                             , resultId :: T.Text} deriving Show

data Resultset = Resultset { offset :: Int
                           , count :: Int
                           , limit :: Int} deriving (Show, Generic)

data MetaData = MetaData { resultset :: Resultset} deriving (Show, Generic)

data NOAAResponse = NOAAResponse {metadata :: MetaData
                                , results :: [NOAAResult]} deriving (Show, Generic)

instance ToJSON NOAAResult where
    toJSON (NOAAResult uid mindate maxdate name datacoverage resultId) =
        object [ "uid" .= uid
               , "mindate" .= mindate
               , "maxdate" .= maxdate
               , "name" .= name
               , "datacoverage" .= datacoverage
               , "id" .= resultId]

instance ToJSON Resultset
instance ToJSON MetaData
instance ToJSON NOAAResponse

result :: NOAAResult
result = NOAAResult "uid1" "mindate1" "maxdate1" "name1" 1.2 "resultId1"

resultSet :: Resultset
resultSet = Resultset 1 2 3

meta :: MetaData
meta = Main.MetaData resultSet

response :: NOAAResponse
response = NOAAResponse meta [result]


main :: IO ()
main = do
    print response
    print $ encode response

入出力結果(Terminal, Zsh)

% runghc sample1.hs
NOAAResponse {metadata = MetaData {resultset = Resultset {offset = 1, count = 2, limit = 3}}, results = [NOAAResult {uid = "uid1", mindate = "mindate1", maxdate = "maxdate1", name = "name1", datacoverage = 1.2, resultId = "resultId1"}]}
"{\"metadata\":{\"resultset\":{\"count\":2,\"limit\":3,\"offset\":1}},\"results\":[{\"maxdate\":\"maxdate1\",\"id\":\"resultId1\",\"name\":\"name1\",\"mindate\":\"mindate1\",\"datacoverage\":1.2,\"uid\":\"uid1\"}]}"
%