Haskell - 実践Haskell - Aesonfを使ったJSONデータの処理 - データ型をFromJSONとToJSONのインスタンスにする - ToJSON
入門Haskellプログラミング (Will Kurt(著)、株式会社クイープ(監修、翻訳)、翔泳社)の UNIT 7(実践Haskell)、LESSON 40(Aesonfを使ったJSONデータの処理)、40.3(データ型をFromJSONとToJSONのインスタンスにする)、クイックチェック 40-4の解答を求めてみる。
軽量マークアップ言語
json-lesson/package.yaml
name: json-lesson
version: 0.1.0.0
github: "githubuser/json-lesson"
license: BSD-3-Clause
author: "Author name here"
maintainer: "example@example.com"
copyright: "2025 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
- aeson
- bytestring
- text
default-extensions:
- OverloadedStrings
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
コード
json-lesson/app/Main.hs
module Main (main) where
-- import Lib
import qualified Data.Text as T
import qualified Data.ByteString.Lazy as B
import Data.Aeson
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 fname lname) = object [
"firstName" .= fname,
"lastName" .= lname
]
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
errorRawJson :: B.ByteString
errorRawJson = "{\"firstName\":\"first name\",\"lastName\"}"
errorDecoded :: Maybe Name
errorDecoded = decode errorRawJson
errorEitherDecoded :: Either String Name
errorEitherDecoded = eitherDecode errorRawJson
main :: IO ()
main = do
print name
print encoded
print decoded
print eitherDecoded
print errorRawJson
print errorDecoded
print errorEitherDecoded
入出力結果(Terminal, Zsh)
% stack run
json-lesson-0.1.0.0: unregistering (local file changes: app/Main.hs)
json-lesson> build (lib + exe) with ghc-9.8.4
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..
[1 of 2] Compiling Main [Source file changed]
/Users/.../json-lesson/app/Main.hs:14:5: warning: [GHC-62161] [-Wincomplete-patterns]
Pattern match(es) are non-exhaustive
In an equation for ‘parseJSON’:
Patterns of type ‘Value’ not matched:
Array _
String _
Number _
Bool _
...
|
14 | parseJSON (Object v) = Name <$> v.: "firstName" <*> v.: "lastName"
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[3 of 3] Linking .stack-work/dist/aarch64-osx/ghc-9.8.4/build/json-lesson-exe/json-lesson-exe [Objects changed]
ld: warning: -U option is redundant when using -undefined dynamic_lookup
json-lesson> copy/register
Installing library in /Users/.../json-lesson/.stack-work/install/aarch64-osx/27e00dd04a6f7fc061662d4eebb16cc69859af4840b4ab18e626ce23aacafb60/9.8.4/lib/aarch64-osx-ghc-9.8.4/json-lesson-0.1.0.0-5hrW8Xn7EXr6hNkAQFVUwP
Installing executable json-lesson-exe in /Users/.../json-lesson/.stack-work/install/aarch64-osx/27e00dd04a6f7fc061662d4eebb16cc69859af4840b4ab18e626ce23aacafb60/9.8.4/bin
Registering library for json-lesson-0.1.0.0..
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"})
"{\"firstName\":\"first name\",\"lastName\"}"
Nothing
Left "Unexpected \"}\", expecting :"
%