How to write a FromJSON and ToJSON instance for unsupported field (CI Text)

I’m using aeson template haskell to generate instances for a record which I get from postgres.
I’m using the postgres citext which I unmarshal into the CI Text from case-insensitive package.
Unfortunately CI Text has no support for aeson. How can I manually write this instance for CI Text in my own codebase?

I’m new to haskell so it’s difficult to figure this out from only the hackage documentations.

This is the error I get:

This is the case-insensitve docs:
https://hackage.haskell.org/package/case-insensitive-1.2.1.0/docs/Data-CaseInsensitive.html

The aeson documentation has a section on writing instances by hand, which is probably necessary in this case: Data.Aeson. In this case I think the instances would be pretty simple, something like:

instance (FromJSON a, FoldCase a) => FromJSON (CI a) where
    parseJSON v = do
      x <- parseJSON v
      pure (mk x)

instance ToJSON a => ToJSON (CI a) where
    toJSON x = toJSON (original x)
    toEncoding x = toEncoding (original x)

(I haven’t tested this code)

Thanks @jaror. I went github code diving, and was able to do something which seems to work. Thanks!

This is what I did:


instance FromJSON (CI Text) where
  parseJSON = fmap CI.mk . parseJSON

instance ToJSON (CI Text) where
  toJSON = toJSON . CI.original
1 Like