I'm trying to parse JSON to produce a type with multiple constructors. The challenge is that the type is encoded in the name of a key which contains the required data. In theory I could use a bunch of .:?
calls and then check if given key returns Just
but I think there must be a better way. I looked at asum
but this didn't help me much (probably because of my unfamiliarity with it).
import Data.Aeson
import Data.Time.Clock
data Request = Req1 { id :: String, properties :: Value }
| Req2 { id :: String, properties :: Value }
| Req3 { id :: String, time :: UTCTime }
instance FromJSON Request where
parseJSON = withObject "message" $ \o ->
-- ???
Example requests:
{"req1": {"id": "345", "p1": "v1", "p2": "v2"}}
{"req2": {"id": "654", "p3", "v3"}}
{"req3": {"id": "876", "time": 1234567890}}