Skip to content

Instantly share code, notes, and snippets.

@timjb
Created March 18, 2019 13:55
Show Gist options
  • Save timjb/8d2a71c06fcc0c475e03d8840c44ad32 to your computer and use it in GitHub Desktop.
Save timjb/8d2a71c06fcc0c475e03d8840c44ad32 to your computer and use it in GitHub Desktop.
FTypes JSON example
-- Initial ftypes-json.cabal generated by cabal init. For further
-- documentation, see http://haskell.org/cabal/users-guide/
name: ftypes-json
version: 0.1.0.0
-- synopsis:
-- description:
homepage: https://github.com/timjb/ftypes
license: MIT
license-file: LICENSE
author: Tim Baumann
maintainer: [email protected]
-- copyright:
-- category:
build-type: Simple
-- extra-source-files:
cabal-version: >=1.10
library
exposed-modules:
JSONFormat
GithubUser
-- other-modules:
-- other-extensions:
build-depends:
base,
ftypes,
aeson,
text
hs-source-dirs: .
default-language: Haskell2010
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RecordWildCards #-}
module GithubUser where
import JSONFormat
import FTypes
import FTypes.Compose
import FTypes.Trafo
--import FTypes.Const
import Data.Functor.Identity
import Data.Aeson ((.=), (.:))
import qualified Data.Aeson as A
import qualified Data.Text as T
newtype GithubUserId
= GithubUserId
{ unGithubUserId :: Integer
} deriving (A.FromJSON, A.ToJSON)
newtype Url
= Url
{ unUrl :: T.Text
} deriving (A.ToJSON, A.FromJSON)
-- https://api.github.com/users/timjb
data GithubUser
= GithubUser
{ userLogin :: T.Text
, userId :: GithubUserId
, userAvatarUrl :: Url
-- ...
}
instance A.ToJSON GithubUser where
toJSON ghUser =
A.object
[ "login" .= userLogin ghUser
, "id" .= userId ghUser
, "avatar_url" .= userAvatarUrl ghUser
]
instance A.FromJSON GithubUser where
parseJSON =
A.withObject "GithubUser" $ \obj -> do
userLogin <- obj .: "login"
userId <- obj .: "id"
userAvatarUrl <- obj .: "avatar_url"
pure GithubUser {..}
{-
-- Alternative:
instance A.FromJSON GithubUser where
parseJSON =
A.withObject "GithubUser" $ \obj -> do
GithubUser
<$> (obj .: "login")
<*> (obj .: "id")
<*> (obj .: "avatar_url")
-}
data FGithubUser (f :: * -> *)
= FGithubUser
{ fuserLogin :: f T.Text
, fuserId :: f GithubUserId
, fuserAvatarUrl :: f Url
-- ...
}
timjb :: FGithubUser Identity
timjb =
FGithubUser
{ fuserLogin = Identity "timjb"
, fuserId = Identity (GithubUserId 134)
, fuserAvatarUrl = Identity (Url "https://blabla.com/")
-- ...
}
instance FFunctor FGithubUser where
ffmap f ghUser =
FGithubUser
{ fuserLogin = f (fuserLogin ghUser)
, fuserId = f (fuserId ghUser)
, fuserAvatarUrl = f (fuserAvatarUrl ghUser)
-- ...
}
instance FTraversable FGithubUser where
fsequenceA ghUser =
FGithubUser
<$> getCompose (fuserLogin ghUser)
<*> getCompose (fuserId ghUser)
<*> getCompose (fuserAvatarUrl ghUser)
instance FApplicative FGithubUser where
fpure v =
FGithubUser
{ fuserLogin = v
, fuserId = v
, fuserAvatarUrl = v
-- ...
}
r <<*>> s =
FGithubUser
{ fuserLogin = fuserLogin r $$ fuserLogin s
, fuserId = fuserId r $$ fuserId s
, fuserAvatarUrl = fuserAvatarUrl r $$ fuserAvatarUrl s
-- ...
}
ghUserJSONFormat :: FGithubUser JSONField
ghUserJSONFormat =
FGithubUser
{ fuserLogin = field "login"
, fuserId = field "id"
, fuserAvatarUrl = field "avatar_url"
-- ...
}
{-# LANGUAGE FlexibleContexts #-}
module JSONFormat where
import FTypes
import Control.Applicative (Const (..))
import Data.Functor.Identity (Identity (..))
import Data.Aeson ((.=), (.:))
import qualified Data.Aeson as A
import qualified Data.Aeson.Types as A
import qualified Data.Text as T
data JSONFormat x
= JSONFormat
{ toJSON :: x -> A.Value
, parseJSON :: A.Value -> A.Parser x
}
defaultFormat :: (A.ToJSON x, A.FromJSON x) => JSONFormat x
defaultFormat =
JSONFormat
{ toJSON = A.toJSON
, parseJSON = A.parseJSON
}
data JSONField x
= JSONField
{ fieldName :: T.Text
, fieldFormat :: JSONFormat x
}
field :: (A.ToJSON x, A.FromJSON x) => T.Text -> JSONField x
field name =
JSONField
{ fieldName = name
, fieldFormat = defaultFormat
}
serializeField :: A.KeyValue kv => JSONField x -> x -> kv
serializeField field val =
fieldName field .= toJSON (fieldFormat field) val
parseField :: JSONField x -> A.Object -> A.Parser x
parseField field obj = do
jsonVal <- obj .: fieldName field
parseJSON (fieldFormat field) jsonVal
objectFormat
:: (FFunctor r, FApplicative r, FTraversable r)
=> String
-> r JSONField
-> JSONFormat (r Identity)
objectFormat name fields =
JSONFormat
{ toJSON = serialize
, parseJSON = parse
}
where
parse =
A.withObject name $ \obj ->
ftraverse' (\field -> parseField field obj) fields
serialize val =
A.object $
ftoList $
fliftA2 (\(Identity v) field -> Const (serializeField field v)) val fields
Copyright (c) 2016 Tim Baumann
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Distribution.Simple
main = defaultMain
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment