計算機科学のブログ

実践Haskell Aesonを使ったJSONデータの処理 データ型をFromJSONとToJSONのインスタンスにする FromJSONとToJSONのインスタンスを独自に記述する parseJSON関数、Maybe、(<$>)、(<*>)、(.:)

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

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
library:
  source-dirs: src

executables:
  json-lesson-exe:
    main:                Main.hs
    source-dirs:         app
    ghc-options:
    - -threaded
    - -rtsopts
    - -with-rtsopts=-N
    dependencies:
    - json-lesson
    - aeson
    - bytestring
    - text
    default-extensions:
    - OverloadedStrings
    # - DeriveGeneric

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

コード

app/Main.hs

module Main where

import Data.Aeson
import qualified Data.ByteString as T
import Data.ByteString.Lazy as B
import Data.ByteString.Lazy.Char8 as BC
import Data.Text as T
import qualified Data.Text.Encoding as E
-- import GHC.Generics (Generic)
import Lib ()

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

instance FromJSON Name where
  parseJSON (Object v) =
    Name <$> v .: "firstName" <*> v .: "lastName"

nameJson :: BC.ByteString
nameJson = "{\"firstName\": \"first name\", \"lastName\": \"last name\"}"

nameJsonError :: BC.ByteString
nameJsonError = "{}"

names :: [Maybe Name]
names = Prelude.map decode [nameJson, nameJsonError]

main :: IO ()
main = do
  mapM_ print names

入出力結果(Terminal, Zsh)

% stack build
json-lesson-0.1.0.0: unregistering (local file changes: app/Main.hs)
json-lesson> build (lib + exe)
Preprocessing library for json-lesson-0.1.0.0..
Building library for json-lesson-0.1.0.0..
Preprocessing executable 'json-lesson-exe' for json-lesson-0.1.0.0..
Building executable 'json-lesson-exe' for json-lesson-0.1.0.0..
[2 of 2] Compiling Main
Linking .stack-work/dist/x86_64-osx/Cabal-3.4.1.0/build/json-lesson-exe/json-lesson-exe ...
json-lesson> copy/register
Installing library in /Users/…/json-lesson/.stack-work/install/x86_64-osx/517038c0363b4c0a7ccbe3fd94330b03ef892e9dc18133de80a96d8183f01a77/9.0.2/lib/x86_64-osx-ghc-9.0.2/json-lesson-0.1.0.0-DrW14hPJvvsAt58QhciBQU
Installing executable json-lesson-exe in /Users/…/json-lesson/.stack-work/install/x86_64-osx/517038c0363b4c0a7ccbe3fd94330b03ef892e9dc18133de80a96d8183f01a77/9.0.2/bin
Registering library for json-lesson-0.1.0.0..
% stack exec json-lesson-exe
Just (Name {firstName = "first name", lastName = "last name"})
Nothing
%