Oguz Bilgic Oguz Bilgic - 5 months ago 9
JSON Question

Attribute names for decoding JSON

data Message = Message {
type :: String
} deriving (Eq, Show, Data, Typeable)


-- main funciton
let m = decodeJSON "{\"type\":\"event\"}" :: Message
putStrLn (type m)


Haskell newbie here, Im trying to decode messages I receive from a websocket connection. However Haskell doesn't let me use the 'type' word as an attribute for the Message type. What would be the way to decode this JSON message if attributes contain words such as type.

Answer

using type as a record type is not allowed, you will have to make some changes.

If you are willing to use Aeson instead of the json package, you can do this by writing the instance by hand, as follows....

data Message = Message {
  type' :: String
  } deriving (Eq, Show)

instance FromJSON Message where
   parseJSON (Object v) = Message <$> v .: "type"

main = do
  let m = decode "{\"type\":\"event\"}" :: Maybe Message
  putStrLn (show $ fmap type' m)

You will have to change the flow of the program a little bit....

Comments