1

I have a data:

data MyData = MyData { a :: String, b :: Integer, c :: Bool } 
                      deriving (Generic)

instance FromJSON MyData
instance ToJSON MyData

In fact, I have many more fields in MyData.

I want to parse 1 or 2 fields manually because in MyData they're called slightly different than in the real JSON object, while still being able to have FromJSON and ToJSON or something like that. Is it possible? Or should I in this case parse all the fields manually and not use FromJSON / ToJSON?

Alec
  • 31,829
  • 7
  • 67
  • 114
Orado
  • 13
  • 2
  • 1
    Relevant: [Parse JSON with fieldnames that contain reserved keywords](http://stackoverflow.com/questions/18410686/parse-json-with-fieldnames-that-contain-reserved-keywords) – duplode Dec 04 '16 at 16:51

1 Answers1

2

You'll want to take a look at the template Haskell deriving abilities of aeson. There is an option there which helps you rename fields. For example, say I want to rename the color field to colour in the declaration below:

data MyData = MyData { address :: String
                     , streetNumber :: Integer
                     , isApartment :: Bool
                     , color :: String
                     }

Then, instead of deriving Generic, I add the following

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

data MyData = MyData { address :: String
                     , streetNumber :: Integer
                     , isApartment :: Bool
                     , color :: String
                     }

$(deriveJSON defaultOptions{
    constructorTagModifier = \f -> if f == "color" then "colour" else f 
  } ''MyData)

Then my ToJSON and FromJSON instances have appropriately named fields.

Alec
  • 31,829
  • 7
  • 67
  • 114
  • by the way, is there a way to generate a list of "imports" or "imports qualified" with template haskell so it compiles as if I were to add them manually? – Orado Dec 04 '16 at 19:09
  • @Orado Not that I know of. Maybe someone else will have an idea for that. – Alec Dec 04 '16 at 19:16
  • 1
    alright. is it possible not to parse all the fields in `FromJSON` implementation, but only ones I want, because others are irrelevant for me? – Orado Dec 05 '16 at 04:22
  • @Orado That happens automatically. If your JSON object has more fields than you need, the extra fields are just ignored. – Alec Dec 05 '16 at 04:31
  • You should probably derive `Generic` anyway; all sorts of other classes will want it for defaults. – dfeuer Dec 05 '16 at 05:25