Skip to content

Instantly share code, notes, and snippets.

@alexpeits
Created October 1, 2018 09:17
Show Gist options
  • Save alexpeits/4bb5ab7d4cdc5b86b1d6793cb04bb16e to your computer and use it in GitHub Desktop.
Save alexpeits/4bb5ab7d4cdc5b86b1d6793cb04bb16e to your computer and use it in GitHub Desktop.
Merge datatypes with Aeson
{-# LANGUAGE TypeOperators, FlexibleInstances, DeriveGeneric, OverloadedStrings #-}
module JSON where
import GHC.Generics
import Data.Aeson
import qualified Data.HashMap.Lazy as M
data A = A {a :: String} deriving (Show, Generic)
data B = B {b :: Float} deriving (Show, Generic)
instance ToJSON A
instance ToJSON B
data Merge a b = Merge a b deriving Show
instance ToJSON (Merge A B) where
toJSON (Merge a b) = mergeJSON [toJSON a, toJSON b]
mergeJSON :: [Value] -> Value
mergeJSON = Object . M.unions . map (\(Object x) -> x)
aVal :: A
aVal = A "str"
bVal :: B
bVal = B 12.34
cVal :: Merge A B
cVal = Merge aVal bVal
-- then do: encode cVal --> {"a": "str", "b": 12.34}
@alexpeits
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment