Created
October 1, 2018 09:17
-
-
Save alexpeits/4bb5ab7d4cdc5b86b1d6793cb04bb16e to your computer and use it in GitHub Desktop.
Merge datatypes with Aeson
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://gist.github.com/cdparks/32217e570048dd2066549272b1640b5b