Home > OS >  Escaping Haskell record's field
Escaping Haskell record's field

Time:11-27

Question

Is there a way to create a record with a field called "data"?

data MyRecord =
  MyRecord {
    otherField :: String,
    data       :: String  -- compilation error
  }

Why do I need it?

I've been writing a wrapper around a JSON API using Aeson and the remote service decided to call one of the fields data.

{
  pagination: {
    ..
  },
  data: [ 
    { .. },
    { .. },
  ]
}

CodePudding user response:

Yes, you can name the field something else than data, like:

data MyRecord =
  MyRecord {
    otherField :: String,
    recordData :: String
  }

And then derive a ToJSON with a key modifier:

labelMapping :: String -> String
labelMapping "recordData" = "data"
labelMapping x = x

instance ToJSON MyRecord where
    toJSON = genericToJSON defaultOptions {
            fieldLabelModifier = labelMapping
        }

instance FromJSON Coord where
    parseJSON = genericParseJSON defaultOptions {
            fieldLabelModifier = labelMapping
        }
  • Related