how to handle capital case in JSON?

564 views Asked by At

This is a stupid question, and I have tried to understand from different tutorials. When having a JSON with capital case Haskell crashes as explained by others (https://mail.haskell.org/pipermail/beginners/2013-October/012865.html). As suggested it could be solved with deriving from deriveFromJSON. DeriveJSON requires a function input, how should I write the derive statement in the below code? I am missing something in my understanding, and would appreciate any help.

import Data.Aeson.TH

data Person = Person { 
        Foo :: String
        , bar :: String
    } deriving (Eq, Show, deriveJSON)

main = do 
let b = Person "t" "x" 
print b  
2

There are 2 answers

2
hammar On BEST ANSWER

deriveJSON and friends are Template Haskell functions which will generate instances for you. As such, you should not try to list them in the deriving clause. Instead, call them in a splice at the top level like this:

{-# LANGUAGE TemplateHaskell #-}
import Data.Aeson.TH

data Person = Person { 
    foo :: String,
    bar :: String
} deriving (Eq, Show)

$(deriveJSON defaultOptions ''Person)

As mentioned in the mailing list, you can customize the field names by overriding the fieldLabelModifier function of the defaultOptions record, for example this will change the JSON name of foo to Foo:

$(deriveFromJSON defaultOptions {
    fieldLabelModifier = let f "foo" = "Foo"
                             f other = other
                         in f
} ''Person)
0
Cubic On

Do you have any control of the instance being generated? If so, don't emit keys starting with capital letters.

If not: Just define the instance yourself instead of deriving it. It's just a couple lines of code.