简体   繁体   中英

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.

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....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM