Skip to content

Instantly share code, notes, and snippets.

@joncol
Created November 3, 2022 10:37
Show Gist options
  • Save joncol/2fb38d2d1f20fe67c4a93bb86e50bd3a to your computer and use it in GitHub Desktop.
Save joncol/2fb38d2d1f20fe67c4a93bb86e50bd3a to your computer and use it in GitHub Desktop.
ModKeys
module ModKeys where
import Data.Aeson
import Data.Text (Text)
import GHC.Generics (Generic)
import qualified Data.Aeson as Aeson
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Text.Encoding as E
import qualified Data.Text.IO as TIO
data Foo = Foo
{ name :: Text
, x :: X
}
deriving (Generic, Show)
aesonOptions :: Aeson.Options
aesonOptions =
defaultOptions
{ fieldLabelModifier = \x -> "field_" <> x
, constructorTagModifier = \x -> "cons_" <> x
, sumEncoding = ObjectWithSingleField
, unwrapUnaryRecords = True
}
instance ToJSON Foo where
toJSON = genericToJSON aesonOptions
toEncoding = genericToEncoding aesonOptions
data X = A String | B Int
deriving (Eq, Show, Generic)
instance ToJSON X where
toJSON = genericToJSON aesonOptions
toEncoding = genericToEncoding aesonOptions
instance FromJSON X where
parseJSON = genericParseJSON aesonOptions
keyFunc :: IO ()
keyFunc = do
let something =
Foo
{ name = "Dummy"
, x = A "Foo"
}
-- I would want this to be: {"field_name": "Dummy", "cons_A": "Foo"},
-- instead of: {"field_name":"Dummy","field_x":{"cons_A":"Foo"}}
TIO.putStrLn . E.decodeUtf8 . LBS.toStrict . encode $ something
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment