計算機科学のブログ

実践Haskell Aesonを使ったJSONデータの処理 データ型をFromJSONとToJSONのインスタンスにする FromJSONとToJSONのインスタンスを独自に記述する toJSON関数、(.=)

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

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
  ( FromJSON (parseJSON),
    KeyValue ((.=)),
    ToJSON (toJSON),
    Value (Object),
    decode,
    encode,
    object,
    (.:),
  )
import qualified Data.ByteString as T
import Data.ByteString.Lazy as B ()
import Data.ByteString.Lazy.Char8 as BC ()
import Data.Text as T (Text)
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"

instance ToJSON Name where
  toJSON (Name firstName lastName) =
    object
      [ "firstName" .= firstName,
        "lastName" .= lastName
      ]

name :: Name
name =
  Name
    { firstName = "名前",
      lastName = "苗字"
    }

main :: IO ()
main = do
  print name
  print $ encode name
  print (decode $ encode name :: Maybe Name)

入出力結果(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/k/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/k/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     
Name {firstName = "\21517\21069", lastName = "\33495\23383"}
"{\"firstName\":\"\229\144\141\229\137\141\",\"lastName\":\"\232\139\151\229\173\151\"}"
Just (Name {firstName = "\21517\21069", lastName = "\33495\23383"})
%