Skip to content

Instantly share code, notes, and snippets.

@fumieval
Created November 9, 2019 04:40
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save fumieval/5c89205d418d5f9cafac801afbe94969 to your computer and use it in GitHub Desktop.
{-# 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