3

I have a Haskell record

data User = User
    { email :: Text
    , token :: Text
    }

and I want to ignore the value of "token" in any input JSON. For example, if the input JSON is

{
    "email": "foo@bar.com",
    "token": "abc123"
}

I want the resulting User object to contain User { email = "foo@bar.com", token = "" }.

I defined the following:

instance FromJSON User where
    parseJSON (Object v) =
        User <$> v .:  "email"
             <*> v .:? "" .!= "" -- token

    parseJSON _ = fail "Invalid User"

Is there a better way to set the value of the token field then v .:? "" .!= "", ignoring the "token": "abc123" in the JSON?

I tried

instance FromJSON User where
    parseJSON (Object v) =
        User <$> v .:  "email"
             <*> "" -- token

    parseJSON _ = fail "Invalid User"

but it will not compile because the <*> "" needs to be a Parser Text.

Ralph
  • 31,584
  • 38
  • 145
  • 282

1 Answers1

5

Have you tried this one?

User <$> v .: "email" <*> pure ""

The pure function comes from Control.Applicative module. In this case it constructs a trivial parser that delivers "" as its result. If you are not familiar with applicative functors you can read about them on typeclassopedia.

Piotr Miś
  • 981
  • 5
  • 6