計算機科学のブログ

実践Haskell Aesonを使ったJSONデータの処理 ToJSON

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

json-lesson/package.yaml

name:                json-lesson
version:             0.1.0.0
github:              "githubuser/json-lesson"
license:             BSD3
author:              "Author name here"
maintainer:          "example@example.com"
copyright:           "2022 Author name here"

extra-source-files:
- README.md
- CHANGELOG.md

# Metadata used when publishing your package
# synopsis:            Short description of your package
# category:            Web

# To avoid duplicated efforts in documentation and dealing with the
# complications of embedding Haddock markup inside cabal files, it is
# common to point users to the README.md file.
description:         Please see the README on GitHub at <https://github.com/githubuser/json-lesson#readme>

dependencies:
- base >= 4.7 && < 5
- text
- aeson
- bytestring


ghc-options:
- -Wall
- -Wcompat
- -Widentities
- -Wincomplete-record-updates
- -Wincomplete-uni-patterns
- -Wmissing-export-lists
- -Wmissing-home-modules
- -Wpartial-fields
- -Wredundant-constraints

library:
  source-dirs: src

executables:
  json-lesson-exe:
    main:                Main.hs
    source-dirs:         app
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - json-lesson

tests:
  json-lesson-test:
    main:                Spec.hs
    source-dirs:         test
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - json-lesson

default-extensions:
  - OverloadedStrings
  - DeriveGeneric

json-lesson/json-lesson.cabal

cabal-version: 1.12

-- This file has been generated from package.yaml by hpack version 0.34.4.
--
-- see: https://github.com/sol/hpack

name:           json-lesson
version:        0.1.0.0
description:    Please see the README on GitHub at <https://github.com/githubuser/json-lesson#readme>
homepage:       https://github.com/githubuser/json-lesson#readme
bug-reports:    https://github.com/githubuser/json-lesson/issues
author:         Author name here
maintainer:     example@example.com
copyright:      2022 Author name here
license:        BSD3
license-file:   LICENSE
build-type:     Simple
extra-source-files:
    README.md
    CHANGELOG.md

source-repository head
  type: git
  location: https://github.com/githubuser/json-lesson

library
  exposed-modules:
      Lib
  other-modules:
      Paths_json_lesson
  hs-source-dirs:
      src
  default-extensions:
      OverloadedStrings
      DeriveGeneric
  ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints
  build-depends:
      aeson
    , base >=4.7 && <5
    , bytestring
    , text
  default-language: Haskell2010

executable json-lesson-exe
  main-is: Main.hs
  other-modules:
      Paths_json_lesson
  hs-source-dirs:
      app
  default-extensions:
      OverloadedStrings
      DeriveGeneric
  ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints -threaded -rtsopts -with-rtsopts=-N
  build-depends:
      aeson
    , base >=4.7 && <5
    , bytestring
    , json-lesson
    , text
  default-language: Haskell2010

test-suite json-lesson-test
  type: exitcode-stdio-1.0
  main-is: Spec.hs
  other-modules:
      Paths_json_lesson
  hs-source-dirs:
      test
  default-extensions:
      OverloadedStrings
      DeriveGeneric
  ghc-options: -Wall -Wcompat -Widentities -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-export-lists -Wmissing-home-modules -Wpartial-fields -Wredundant-constraints -threaded -rtsopts -with-rtsopts=-N
  build-depends:
      aeson
    , base >=4.7 && <5
    , bytestring
    , json-lesson
    , text
  default-language: Haskell2010

コード

json-lesson/app/Main.hs

module Main (main) where

import Data.Aeson (encode)
import Lib
  ( Metadata (..),
    NOAAResponse (..),
    NOAAResult (..),
    Resultset (..),
  )

res :: NOAAResponse
res =
  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"
            }
        ]
    }

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

json-lesson/src/Lib.hs

module Lib
  ( Metadata (..),
    NOAAResponse (..),
    NOAAResult (..),
    Resultset (..),
  )
where

import Data.Aeson (KeyValue ((.=)), ToJSON (toJSON), object)
import Data.Text as T (Text)
import GHC.Generics (Generic)

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

instance ToJSON NOAAResult where
  toJSON (NOAAResult u mind maxd n dc ri) =
    object
      [ "uid" .= u,
        "mindate" .= mind,
        "maxdate" .= maxd,
        "name" .= n,
        "datacoverage" .= dc,
        "resultId" .= ri
      ]

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

instance ToJSON Resultset

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

instance ToJSON Metadata

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

instance ToJSON NOAAResponse

入出力結果(Terminal, Zsh)

% stack exec json-lesson-exe
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\":[{\"datacoverage\":1.2,\"maxdate\":\"maxdate1\",\"mindate\":\"mindate1\",\"name\":\"name1\",\"resultId\":\"resultId1\",\"uid\":\"uid1\"}]}"
%