計算機科学のブログ

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

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

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

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

json :: B.ByteString
json = "{\"firstName\": \"first name\", \"lastName\": \"last name\"}"

decoded :: Maybe Name
decoded = decode json

eitherDecoded :: Either String Name
eitherDecoded = eitherDecode json

wrongJson :: B.ByteString
wrongJson = "{}"

wrongDecoded :: Maybe Name
wrongDecoded = decode wrongJson

wrongEitherDecoded :: Either String Name
wrongEitherDecoded = eitherDecode wrongJson

main :: IO ()
main = do
  print json
  print decoded
  print eitherDecoded
  print wrongJson
  print wrongDecoded
  print wrongEitherDecoded

json-lesson/src/Lib.hs

module Lib
  ( Name (..),
  )
where

import Data.Aeson (FromJSON (parseJSON), Value (Object), (.:))
import Data.Text as T (Text)

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

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

入出力結果(Terminal, Zsh)

% stack exec json-lesson-exe
"{\"firstName\": \"first name\", \"lastName\": \"last name\"}"
Just (Name {firstName = "first name", lastName = "last name"})
Right (Name {firstName = "first name", lastName = "last name"})
"{}"
Nothing
Left "Error in $: key \"firstName\" not found"
%