The easiest and quickest way to encode a Haskell data type to JSON with Aeson is using generics.
{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics
import Data.Text
import Data.Aeson
import Data.ByteString.Lazy
First let us create a data type Person:
data Person = Person { firstName :...
{-# LANGUAGE OverloadedStrings #-}
module Main where
import Data.Aeson
main :: IO ()
main = do
let example = Data.Aeson.object [ "key" .= (5 :: Integer), "somethingElse" .= (2 :: Integer) ] :: Value
print . encode $ example
Sometimes, we want some fields in the JSON string to be optional. For example,
data Person = Person { firstName :: Text
, lastName :: Text
, age :: Maybe Int
}
This can be achieved by
import Data.Aeson.TH
$(deriveJSON ...