Skip to content

Instantly share code, notes, and snippets.

@fumieval

fumieval/prefix.hs

Created Nov 9, 2019
Embed
What would you like to do?
{-# 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