jules jules - 1 month ago 17
JSON Question

Writing custom instances for JSON date data in Aeson

I have JSON date data in the following form:

{"date": "2015-04-12"}


and a corresponding haskell type:

data Date = Date {
year :: Int
, month :: Int
, day :: Int
}


How can I write the custom
FromJSON
and
ToJSON
functions for the
Aeson library?
Deriving the instances does not work because of the formatting.

Answer

You have convert y/m/d to/from string

{-# 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
            ps@(~[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