Damian Nadales
Damian Nadales

Reputation: 5027

Aeson: parse enumerated data types

How can I declare an instance of FromJSON of the following data type:

data Privacy = Everyone | 
           AllFriends | 
           FriendsOfFriends | 
           Self

So that the following string to enumerated data type is honored:

"EVERYONE" -> Everyone
"ALL_FRIENDS" -> AllFriends
"FRIENDS_OF_FRIENDS" -> FriendsOfFriends
"SELF" -> Self
_ -> Parsing error

A possible solution is hinted here, but I cannot make that code compile.

Thanks!

Upvotes: 5

Views: 688

Answers (3)

sportanova
sportanova

Reputation: 124

This way involves less boilerplate, but it may not be as efficient due to the T.unpack

data Privacy = Everyone | AllFriends | FriendsOfFriends | Self deriving (Read, Show)

instance FromJSON Privacy where
  parseJSON (String s) = fmap read (pure $ T.unpack s)
  parseJSON _ = mzero

Upvotes: 5

ErikR
ErikR

Reputation: 52029

The FromJSON definition should read:

instance FromJSON Privacy where
     parseJSON (Object v) = createPrivacy <$> (v .: "value")

Complete working example:

{-# LANGUAGE OverloadedStrings #-}

import Data.Text
import Data.Aeson
import Control.Applicative
import Control.Monad

data Privacy = Everyone |
               AllFriends |
               FriendsOfFriends |
               Self
  deriving (Show)

instance FromJSON Privacy where
     parseJSON (Object v) = createPrivacy <$> (v .: "value")
     parseJSON _          = mzero

createPrivacy :: String -> Privacy
createPrivacy "EVERYONE" = Everyone
createPrivacy "ALL_FRIENDS" = AllFriends
createPrivacy "FRIENDS_OF_FRIENDS" = FriendsOfFriends
createPrivacy "SELF" = Self
createPrivacy _ = error "Invalid privacy setting!"

main = do
    let a = decode "{\"value\":\"ALL_FRIENDS\",\"foo\":12}" :: Maybe Privacy
    print a

Upvotes: 2

Damian Nadales
Damian Nadales

Reputation: 5027

The solution I found was to use pure from Control.Applicative.

import Control.Applicative ((<$>), (<*>), pure)

data Privacy = Everyone | 
       AllFriends | 
       FriendsOfFriends | 
       Self

instance FromJSON Privacy where
  parseJSON (String s) =  pure $ mkPrivacy s
  parseJSON _ = fail "Failed to parse Privacy object"

instance ToJSON Privacy where
  toJSON Everyone = "EVERYONE"
  toJSON AllFriends = "ALL_FRIENDS"
  toJSON FriendsOfFriends = "FRIENDS_OF_FRIENDS"
  toJSON Self = "SELF"

mkPrivacy :: Text -> Privacy
mkPrivacy "EVERYONE" = Everyone
mkPrivacy "ALL_FRIENDS" = AllFriends
mkPrivacy "FRIENDS_OF_FRIENDS" = FriendsOfFriends
mkPrivacy "SELF" = Self
mkPrivacy _ = error "Invalid privacy token"

Upvotes: 1

Related Questions