計算機科学のブログ

実践Haskell Aesonを使ったJSONデータの処理 データ型をFromJSONとToJSONのインスタンスにする Genericsモジュール、encode関数、decode関数

入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)のUNIT7(実践Haskell)、LESSON 40(Aesonを使ったJSONデータの処理)、40.3(データ型をFromJSONとToJSONのインスタンスにする)、クイックチェック 40-2の解答を求めてみる。

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
  ( decode,
    eitherDecode,
    encode,
  )
import Data.ByteString.Lazy as B
import Lib (Name (..))

name :: Name
name =
  Name
    { firstName = "first name",
      lastName = "last name"
    }

encoded :: B.ByteString
encoded = encode name

decoded :: Maybe Name
decoded = decode encoded

eitherDecoded :: Either String Name
eitherDecoded = eitherDecode encoded

main :: IO ()
main = do
  print name
  print encoded
  print decoded
  print eitherDecoded

json-lesson/src/Lib.hs

module Lib
  ( Name (..),
  )
where

import Data.Aeson
import Data.Text as T
import GHC.Generics

data Name = Name
  { firstName :: T.Text,
    lastName :: T.Text
  }
  deriving (Show, Generic)

instance FromJSON Name

instance ToJSON Name

入出力結果(Terminal, Zsh)

% stack exec json-lesson-exe
Name {firstName = "first name", lastName = "last name"}
"{\"firstName\":\"first name\",\"lastName\":\"last name\"}"
Just (Name {firstName = "first name", lastName = "last name"})
Right (Name {firstName = "first name", lastName = "last name"})
%