Encode package:aeson-combinators

Functions in this module serve as an alternative ToJSON type class. This allows to define for mapping from data type into multiple JSON representations. type level wrapping. There are two way of defining such encoder:
  • Using simple function a -> Value which doesn't require this library
  • Using this library as DSL together with Contravariant
Encode value into (Lazy) ByteString
Value describing encoding of a into a JSON Value. This is essentially just a wrapper around function that should be applied later.

Covariant to map function over input

Given:
>>> :{
data Person = Person
{ name :: String
, age  :: Int
} deriving (Show, Eq)
:}
>>> :{
personEncoder :: Encoder Person
personEncoder = object
[ field "name" string name
, field "age" int age
]
:}
We can extract person from any pair:
>>> :{
-- Using personEncoder definition from example above
pairEncoder2 :: Encoder (Person, a)
pairEncoder2 = contramap fst personEncoder
:}
>>> encode pairEncoder2 (Person "Jane" 42, Nothing)
"{\"age\":42,\"name\":\"Jane\"}"

Divisible and Decidable

Some of you might know library covariant and ask what is a support for other covariant typeclasses. It's not possible to define lawful Divisble instance for JSON Value and by extension it's not possible to define Decidable either. While it is posible to provide somewhat useful unlawful instances for these this library opts to not to do that.
Object Encoder
>>> :{
data Object = Object
{ name :: Text
, age  :: Int
} deriving (Show, Eq)
:}
>>> :{
objectEncoder :: Encoder Object
objectEncoder = object
[ field "name" text name
, field "age" int age
]
:}
>>> encode objectEncoder $ Object "Joe" 30
"{\"age\":30,\"name\":\"Joe\"}"
Object Encoder (alternative)
>>> :set -XRecordWildCards
>>> :{
data Object = Object
{ name :: Text
, age  :: Int
} deriving (Show, Eq)
:}
>>> :{
objectEncoder' :: Encoder Object
objectEncoder' = object' $ \Object{..} ->
[ field' "name" text name
, field' "age" int age
]
:}
>>> encode objectEncoder' $ Object "Joe" 30
"{\"age\":30,\"name\":\"Joe\"}"