Created
November 9, 2019 04:40
-
-
Save fumieval/5c89205d418d5f9cafac801afbe94969 to your computer and use it in GitHub Desktop.
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 AllowAmbiguousTypes #-} | |
{-# LANGUAGE FlexibleContexts #-} | |
{-# LANGUAGE UndecidableInstances #-} | |
{-# LANGUAGE OverloadedStrings #-} | |
{-# LANGUAGE PolyKinds #-} | |
{-# LANGUAGE ScopedTypeVariables #-} | |
{-# LANGUAGE TypeApplications #-} | |
module Data.Aeson.Extras where | |
import Data.Aeson | |
import Data.List (stripPrefix) | |
import Data.Proxy | |
import GHC.Generics | |
import GHC.TypeLits | |
modded :: forall str. KnownSymbol str => Options | |
modded = defaultOptions | |
{ fieldLabelModifier = \x -> maybe x id $ stripPrefix (symbolVal (Proxy @ str)) x | |
, omitNothingFields = True | |
} | |
-- | Strip str from the field names | |
newtype Prefixed str a = Prefixed { unPrefixed :: a } | |
instance (KnownSymbol str, Generic a, GFromJSON Zero (Rep a)) => FromJSON (Prefixed str a) where | |
parseJSON = fmap Prefixed . genericParseJSON (modded @ str) | |
instance (KnownSymbol str, Generic a, GToJSON Zero (Rep a)) => ToJSON (Prefixed str a) where | |
toJSON = genericToJSON (modded @ str) . unPrefixed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment