Skip to content

Instantly share code, notes, and snippets.

@afcondon
Created October 26, 2016 07:42
Show Gist options
  • Save afcondon/2bb3833ffb43986994266d373f9676bb to your computer and use it in GitHub Desktop.
Save afcondon/2bb3833ffb43986994266d373f9676bb to your computer and use it in GitHub Desktop.
Pulling a record (ie naked JSON object) of one of two types out of a JSON string using purescript-argonaut and Alt instance of Either
module Main where
import Prelude
import Control.Alt ((<|>))
import Data.Argonaut (Json, decodeJson, (.?))
import Data.Either (Either)
data Response = A { commandResponse :: String, value :: String }
| B { command :: String, value :: Int }
decodeResponse :: Json -> Either String Response
decodeResponse json = decodeA json <|> decodeB json
decodeA :: Json -> Either String Response
decodeA json = do
obj <- decodeJson json
r <- obj .? "commandResponse"
v <- obj .? "value"
pure (A { commandResponse: r, value: v })
decodeB :: Json -> Either String Response
decodeB json = do
obj <- decodeJson json
r <- obj .? "command"
v <- obj .? "value"
pure (B { command: r, value: v })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment