あなたはなぜ車輪の再発明/文字列から
{-# LANGUAGE OverloadedStrings #-}
{-# OPTIONS_GHC -fno-warn-tabs #-}
import Control.Monad
import Data.Aeson
import qualified Data.Text as T
import Text.Read (readMaybe)
-- import qualified Data.Attoparsec.Text as A
data Date = Date Int Int Int deriving (Read, Show)
instance ToJSON Date where
toJSON (Date y m d) = toJSON $ object [
"date" .= T.pack (str 4 y ++ "-" ++ str 2 m ++ "-" ++ str 2 d)]
where
str n = pad . show where
pad s = replicate (n - length s) '0' ++ s
instance FromJSON Date where
parseJSON = withObject "date" $ \v -> do
str <- v .: "date"
let
[email protected](~[y, m, d]) = T.split (== '-') str
guard (length ps == 3)
Date <$> readNum y <*> readNum m <*> readNum d
where
readNum = maybe (fail "not num") return . readMaybe . T.unpack
-- -- or with attoparsec
-- parseJSON = withObject "date" $ \v -> do
-- str <- v .: "date"
-- [y, m, d] <- either fail return $
-- A.parseOnly (A.decimal `A.sepBy` A.char '-') str
-- return $ Date y m d