Derive ToJSON/FromJSON instances in a more prefix-friendly manner.

LTS Haskell 13.26:
Stackage Nightly 2019-06-21:
Latest on Hackage:

See all snapshots deriveJsonNoPrefix appears in

Apache-2.0 licensed by Yuji Yamamoto

Module documentation for

This version can be pinned in stack with:deriveJsonNoPrefix-,1573


Template Haskell macros to derive ToJSON/FromJSON instances in a more prefix-friendly manner.


Suppose you want to create a JSON like this:

    "id": "ID STRING",
    "max": 0.789,
    "min": 0.123

You’d want to define a record type to derive the instance of ToJSON (and possibly FromJSON) automatically:

{-# LANGUAGE TemplateHaskell #-}

import Data.Aeson.TH

data SomeRecord = SomeRecord
  { id :: String
  , max :: Double
  , min :: Double
  } deriving (Eq, Show)

$(deriveToJSON ''SomeRecord)

But you shouldn’t define such a record because both id, max, and min are predefined functions of Prelude!!

As a workaround, we frequently prefix the record labels with their type name:

data SomeRecord = SomeRecord
  { someRecordId :: String
  , someRecordMax :: Double
  , someRecordMin :: Double
  } deriving (Eq, Show)

Then deriveToJSON with a modified option:

deriveToJSON Json.defaultOptions { fieldLabelModifier = firstLower . drop (length "SomeRecord") } ''SomeRecord

That’s almost exactly what deriveToJsonNoTypeNamePrefix does!!
deriveToJsonNoTypeNamePrefix is essentially defined as:

deriveToJsonNoTypeNamePrefix :: Name -> Q [Dec]
deriveToJsonNoTypeNamePrefix deriver name =
  deriveToJSON Json.defaultOptions { fieldLabelModifier = dropPrefix name } name

So now, you don’t have reimplement the fieldLabelModifier anymore!

import Data.Aeson.DeriveNoPrefix

$(deriveJsonNoTypeNamePrefix ''SomeRecord)

Other libraries which would solve the same problem

  • extensible.
  • And other libraries providing extensible records with ToJSON / FromJSON instances.

So use this package all of them are too heavy in learning cost / dependency footprint / etc.


Changelog for deriveJsonNoPrefix

  • Add tests.
  • Add more detailed README.

Initial release.

comments powered byDisqus