cmdv
cmdv

Reputation: 1753

Check type of incoming JSON structure with AESON

I'm using Yesod to make a single POST endpoint that can handle multiple formats of JSON. These I have called MessageType (see in code bellow).

I'm trying to work out how I could case match against the structure of the JSON that comes in to work out what MessageType it is, for this example I need to check if it is a ProjectCreation.

Want to be able to JSON (projectCreation structure) -> MessageType -> do X

Is there a way to simply case match JSON to work out its type?

data MessageType =
    ProjectCreation { id                 :: ProjectId
                    , permId             :: Maybe UUID
                    , queueId            :: UUID
                    , transactionTimeKey :: Maybe Text
                    , name               :: Text
                    , description        :: Maybe Text
                    , createdOn          :: Maybe UTCTime
                    , createdBy          :: Maybe AgentId
                    , enabled            :: Bool
                    , size               :: Fixed E2
                    }
  | DebtPaymentHistorical {..}
  | PowerForecast {..} 
    ...
  deriving (Show, Read, Eq)

derivePersistField "MessageType"

$(deriveJSON defaultOptions ''MessageType)

Upvotes: 1

Views: 107

Answers (1)

sbditto85
sbditto85

Reputation: 1545

The Aeson Object type is just a HashMap Text Value (docs) so you can use withObject to get an object (assuming all are objects) then do whatever logic you'd like to convert it to the appropriate type. Most likely this would involve checking for specific keys to identify which variant it is or possibly having the json declare what it is in a type field. This of course is by making a manual version of parseJSON in the FromJSON instance, but honestly for anything that isn't completely simple I prefer to do that anyways.

Upvotes: 1

Related Questions